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 "CodeGenTypes.h"
22 #include "SanitizerMetadata.h"
23 #include "clang/AST/ASTContext.h"
24 #include "clang/AST/Attr.h"
25 #include "clang/AST/Decl.h"
26 #include "clang/AST/DeclObjC.h"
27 #include "clang/AST/RecordLayout.h"
28 #include "clang/AST/StmtObjC.h"
29 #include "clang/Basic/SourceManager.h"
30 #include "clang/CodeGen/ConstantInitBuilder.h"
31 #include "llvm/ADT/SmallVector.h"
32 #include "llvm/ADT/StringMap.h"
33 #include "llvm/IR/DataLayout.h"
34 #include "llvm/IR/Intrinsics.h"
35 #include "llvm/IR/LLVMContext.h"
36 #include "llvm/IR/Module.h"
37 #include "llvm/Support/Compiler.h"
38 #include "llvm/Support/ConvertUTF.h"
41 using namespace clang
;
42 using namespace CodeGen
;
46 /// Class that lazily initialises the runtime function. Avoids inserting the
47 /// types and the function declaration into a module if they're not used, and
48 /// avoids constructing the type more than once if it's used more than once.
49 class LazyRuntimeFunction
{
50 CodeGenModule
*CGM
= nullptr;
51 llvm::FunctionType
*FTy
= nullptr;
52 const char *FunctionName
= nullptr;
53 llvm::FunctionCallee Function
= nullptr;
56 LazyRuntimeFunction() = default;
58 /// Initialises the lazy function with the name, return type, and the types
60 template <typename
... Tys
>
61 void init(CodeGenModule
*Mod
, const char *name
, llvm::Type
*RetTy
,
67 SmallVector
<llvm::Type
*, 8> ArgTys({Types
...});
68 FTy
= llvm::FunctionType::get(RetTy
, ArgTys
, false);
71 FTy
= llvm::FunctionType::get(RetTy
, {}, false);
75 llvm::FunctionType
*getType() { return FTy
; }
77 /// Overloaded cast operator, allows the class to be implicitly cast to an
79 operator llvm::FunctionCallee() {
83 Function
= CGM
->CreateRuntimeFunction(FTy
, FunctionName
);
90 /// GNU Objective-C runtime code generation. This class implements the parts of
91 /// Objective-C support that are specific to the GNU family of runtimes (GCC,
92 /// GNUstep and ObjFW).
93 class CGObjCGNU
: public CGObjCRuntime
{
95 /// The LLVM module into which output is inserted
96 llvm::Module
&TheModule
;
97 /// strut objc_super. Used for sending messages to super. This structure
98 /// contains the receiver (object) and the expected class.
99 llvm::StructType
*ObjCSuperTy
;
100 /// struct objc_super*. The type of the argument to the superclass message
101 /// lookup functions.
102 llvm::PointerType
*PtrToObjCSuperTy
;
103 /// LLVM type for selectors. Opaque pointer (i8*) unless a header declaring
104 /// SEL is included in a header somewhere, in which case it will be whatever
105 /// type is declared in that header, most likely {i8*, i8*}.
106 llvm::PointerType
*SelectorTy
;
107 /// Element type of SelectorTy.
108 llvm::Type
*SelectorElemTy
;
109 /// LLVM i8 type. Cached here to avoid repeatedly getting it in all of the
110 /// places where it's used
111 llvm::IntegerType
*Int8Ty
;
112 /// Pointer to i8 - LLVM type of char*, for all of the places where the
113 /// runtime needs to deal with C strings.
114 llvm::PointerType
*PtrToInt8Ty
;
115 /// struct objc_protocol type
116 llvm::StructType
*ProtocolTy
;
118 llvm::PointerType
*ProtocolPtrTy
;
119 /// Instance Method Pointer type. This is a pointer to a function that takes,
120 /// at a minimum, an object and a selector, and is the generic type for
121 /// Objective-C methods. Due to differences between variadic / non-variadic
122 /// calling conventions, it must always be cast to the correct type before
123 /// actually being used.
124 llvm::PointerType
*IMPTy
;
125 /// Type of an untyped Objective-C object. Clang treats id as a built-in type
126 /// when compiling Objective-C code, so this may be an opaque pointer (i8*),
127 /// but if the runtime header declaring it is included then it may be a
128 /// pointer to a structure.
129 llvm::PointerType
*IdTy
;
130 /// Element type of IdTy.
131 llvm::Type
*IdElemTy
;
132 /// Pointer to a pointer to an Objective-C object. Used in the new ABI
133 /// message lookup function and some GC-related functions.
134 llvm::PointerType
*PtrToIdTy
;
135 /// The clang type of id. Used when using the clang CGCall infrastructure to
136 /// call Objective-C methods.
138 /// LLVM type for C int type.
139 llvm::IntegerType
*IntTy
;
140 /// LLVM type for an opaque pointer. This is identical to PtrToInt8Ty, but is
141 /// used in the code to document the difference between i8* meaning a pointer
142 /// to a C string and i8* meaning a pointer to some opaque type.
143 llvm::PointerType
*PtrTy
;
144 /// LLVM type for C long type. The runtime uses this in a lot of places where
145 /// it should be using intptr_t, but we can't fix this without breaking
146 /// compatibility with GCC...
147 llvm::IntegerType
*LongTy
;
148 /// LLVM type for C size_t. Used in various runtime data structures.
149 llvm::IntegerType
*SizeTy
;
150 /// LLVM type for C intptr_t.
151 llvm::IntegerType
*IntPtrTy
;
152 /// LLVM type for C ptrdiff_t. Mainly used in property accessor functions.
153 llvm::IntegerType
*PtrDiffTy
;
154 /// LLVM type for C int*. Used for GCC-ABI-compatible non-fragile instance
156 llvm::PointerType
*PtrToIntTy
;
157 /// LLVM type for Objective-C BOOL type.
159 /// 32-bit integer type, to save us needing to look it up every time it's used.
160 llvm::IntegerType
*Int32Ty
;
161 /// 64-bit integer type, to save us needing to look it up every time it's used.
162 llvm::IntegerType
*Int64Ty
;
163 /// The type of struct objc_property.
164 llvm::StructType
*PropertyMetadataTy
;
165 /// Metadata kind used to tie method lookups to message sends. The GNUstep
166 /// runtime provides some LLVM passes that can use this to do things like
167 /// automatic IMP caching and speculative inlining.
168 unsigned msgSendMDKind
;
169 /// Does the current target use SEH-based exceptions? False implies
170 /// Itanium-style DWARF unwinding.
171 bool usesSEHExceptions
;
172 /// Does the current target uses C++-based exceptions?
173 bool usesCxxExceptions
;
175 /// Helper to check if we are targeting a specific runtime version or later.
176 bool isRuntime(ObjCRuntime::Kind kind
, unsigned major
, unsigned minor
=0) {
177 const ObjCRuntime
&R
= CGM
.getLangOpts().ObjCRuntime
;
178 return (R
.getKind() == kind
) &&
179 (R
.getVersion() >= VersionTuple(major
, minor
));
182 std::string
ManglePublicSymbol(StringRef Name
) {
183 return (StringRef(CGM
.getTriple().isOSBinFormatCOFF() ? "$_" : "._") + Name
).str();
186 std::string
SymbolForProtocol(Twine Name
) {
187 return (ManglePublicSymbol("OBJC_PROTOCOL_") + Name
).str();
190 std::string
SymbolForProtocolRef(StringRef Name
) {
191 return (ManglePublicSymbol("OBJC_REF_PROTOCOL_") + Name
).str();
195 /// Helper function that generates a constant string and returns a pointer to
196 /// the start of the string. The result of this function can be used anywhere
197 /// where the C code specifies const char*.
198 llvm::Constant
*MakeConstantString(StringRef Str
, const char *Name
= "") {
199 ConstantAddress Array
=
200 CGM
.GetAddrOfConstantCString(std::string(Str
), Name
);
201 return Array
.getPointer();
204 /// Emits a linkonce_odr string, whose name is the prefix followed by the
205 /// string value. This allows the linker to combine the strings between
206 /// different modules. Used for EH typeinfo names, selector strings, and a
207 /// few other things.
208 llvm::Constant
*ExportUniqueString(const std::string
&Str
,
209 const std::string
&prefix
,
210 bool Private
=false) {
211 std::string name
= prefix
+ Str
;
212 auto *ConstStr
= TheModule
.getGlobalVariable(name
);
214 llvm::Constant
*value
= llvm::ConstantDataArray::getString(VMContext
,Str
);
215 auto *GV
= new llvm::GlobalVariable(TheModule
, value
->getType(), true,
216 llvm::GlobalValue::LinkOnceODRLinkage
, value
, name
);
217 GV
->setComdat(TheModule
.getOrInsertComdat(name
));
219 GV
->setVisibility(llvm::GlobalValue::HiddenVisibility
);
225 /// Returns a property name and encoding string.
226 llvm::Constant
*MakePropertyEncodingString(const ObjCPropertyDecl
*PD
,
227 const Decl
*Container
) {
228 assert(!isRuntime(ObjCRuntime::GNUstep
, 2));
229 if (isRuntime(ObjCRuntime::GNUstep
, 1, 6)) {
230 std::string NameAndAttributes
;
231 std::string TypeStr
=
232 CGM
.getContext().getObjCEncodingForPropertyDecl(PD
, Container
);
233 NameAndAttributes
+= '\0';
234 NameAndAttributes
+= TypeStr
.length() + 3;
235 NameAndAttributes
+= TypeStr
;
236 NameAndAttributes
+= '\0';
237 NameAndAttributes
+= PD
->getNameAsString();
238 return MakeConstantString(NameAndAttributes
);
240 return MakeConstantString(PD
->getNameAsString());
243 /// Push the property attributes into two structure fields.
244 void PushPropertyAttributes(ConstantStructBuilder
&Fields
,
245 const ObjCPropertyDecl
*property
, bool isSynthesized
=true, bool
247 int attrs
= property
->getPropertyAttributes();
248 // For read-only properties, clear the copy and retain flags
249 if (attrs
& ObjCPropertyAttribute::kind_readonly
) {
250 attrs
&= ~ObjCPropertyAttribute::kind_copy
;
251 attrs
&= ~ObjCPropertyAttribute::kind_retain
;
252 attrs
&= ~ObjCPropertyAttribute::kind_weak
;
253 attrs
&= ~ObjCPropertyAttribute::kind_strong
;
255 // The first flags field has the same attribute values as clang uses internally
256 Fields
.addInt(Int8Ty
, attrs
& 0xff);
259 // For protocol properties, synthesized and dynamic have no meaning, so we
260 // reuse these flags to indicate that this is a protocol property (both set
261 // has no meaning, as a property can't be both synthesized and dynamic)
262 attrs
|= isSynthesized
? (1<<0) : 0;
263 attrs
|= isDynamic
? (1<<1) : 0;
264 // The second field is the next four fields left shifted by two, with the
265 // low bit set to indicate whether the field is synthesized or dynamic.
266 Fields
.addInt(Int8Ty
, attrs
& 0xff);
267 // Two padding fields
268 Fields
.addInt(Int8Ty
, 0);
269 Fields
.addInt(Int8Ty
, 0);
272 virtual llvm::Constant
*GenerateCategoryProtocolList(const
273 ObjCCategoryDecl
*OCD
);
274 virtual ConstantArrayBuilder
PushPropertyListHeader(ConstantStructBuilder
&Fields
,
277 Fields
.addInt(IntTy
, count
);
278 // int size; (only in GNUstep v2 ABI.
279 if (isRuntime(ObjCRuntime::GNUstep
, 2)) {
280 const llvm::DataLayout
&DL
= TheModule
.getDataLayout();
281 Fields
.addInt(IntTy
, DL
.getTypeSizeInBits(PropertyMetadataTy
) /
282 CGM
.getContext().getCharWidth());
284 // struct objc_property_list *next;
286 // struct objc_property properties[]
287 return Fields
.beginArray(PropertyMetadataTy
);
289 virtual void PushProperty(ConstantArrayBuilder
&PropertiesArray
,
290 const ObjCPropertyDecl
*property
,
292 bool isSynthesized
=true, bool
294 auto Fields
= PropertiesArray
.beginStruct(PropertyMetadataTy
);
295 ASTContext
&Context
= CGM
.getContext();
296 Fields
.add(MakePropertyEncodingString(property
, OCD
));
297 PushPropertyAttributes(Fields
, property
, isSynthesized
, isDynamic
);
298 auto addPropertyMethod
= [&](const ObjCMethodDecl
*accessor
) {
300 std::string TypeStr
= Context
.getObjCEncodingForMethodDecl(accessor
);
301 llvm::Constant
*TypeEncoding
= MakeConstantString(TypeStr
);
302 Fields
.add(MakeConstantString(accessor
->getSelector().getAsString()));
303 Fields
.add(TypeEncoding
);
309 addPropertyMethod(property
->getGetterMethodDecl());
310 addPropertyMethod(property
->getSetterMethodDecl());
311 Fields
.finishAndAddTo(PropertiesArray
);
314 /// Ensures that the value has the required type, by inserting a bitcast if
315 /// required. This function lets us avoid inserting bitcasts that are
317 llvm::Value
*EnforceType(CGBuilderTy
&B
, llvm::Value
*V
, llvm::Type
*Ty
) {
318 if (V
->getType() == Ty
)
320 return B
.CreateBitCast(V
, Ty
);
323 // Some zeros used for GEPs in lots of places.
324 llvm::Constant
*Zeros
[2];
325 /// Null pointer value. Mainly used as a terminator in various arrays.
326 llvm::Constant
*NULLPtr
;
328 llvm::LLVMContext
&VMContext
;
332 /// Placeholder for the class. Lots of things refer to the class before we've
333 /// actually emitted it. We use this alias as a placeholder, and then replace
334 /// it with a pointer to the class structure before finally emitting the
336 llvm::GlobalAlias
*ClassPtrAlias
;
337 /// Placeholder for the metaclass. Lots of things refer to the class before
338 /// we've / actually emitted it. We use this alias as a placeholder, and then
339 /// replace / it with a pointer to the metaclass structure before finally
340 /// emitting the / module.
341 llvm::GlobalAlias
*MetaClassPtrAlias
;
342 /// All of the classes that have been generated for this compilation units.
343 std::vector
<llvm::Constant
*> Classes
;
344 /// All of the categories that have been generated for this compilation units.
345 std::vector
<llvm::Constant
*> Categories
;
346 /// All of the Objective-C constant strings that have been generated for this
347 /// compilation units.
348 std::vector
<llvm::Constant
*> ConstantStrings
;
349 /// Map from string values to Objective-C constant strings in the output.
350 /// Used to prevent emitting Objective-C strings more than once. This should
351 /// not be required at all - CodeGenModule should manage this list.
352 llvm::StringMap
<llvm::Constant
*> ObjCStrings
;
353 /// All of the protocols that have been declared.
354 llvm::StringMap
<llvm::Constant
*> ExistingProtocols
;
355 /// For each variant of a selector, we store the type encoding and a
356 /// placeholder value. For an untyped selector, the type will be the empty
357 /// string. Selector references are all done via the module's selector table,
358 /// so we create an alias as a placeholder and then replace it with the real
360 typedef std::pair
<std::string
, llvm::GlobalAlias
*> TypedSelector
;
361 /// Type of the selector map. This is roughly equivalent to the structure
362 /// used in the GNUstep runtime, which maintains a list of all of the valid
363 /// types for a selector in a table.
364 typedef llvm::DenseMap
<Selector
, SmallVector
<TypedSelector
, 2> >
366 /// A map from selectors to selector types. This allows us to emit all
367 /// selectors of the same name and type together.
368 SelectorMap SelectorTable
;
370 /// Selectors related to memory management. When compiling in GC mode, we
372 Selector RetainSel
, ReleaseSel
, AutoreleaseSel
;
373 /// Runtime functions used for memory management in GC mode. Note that clang
374 /// supports code generation for calling these functions, but neither GNU
375 /// runtime actually supports this API properly yet.
376 LazyRuntimeFunction IvarAssignFn
, StrongCastAssignFn
, MemMoveFn
, WeakReadFn
,
377 WeakAssignFn
, GlobalAssignFn
;
379 typedef std::pair
<std::string
, std::string
> ClassAliasPair
;
380 /// All classes that have aliases set for them.
381 std::vector
<ClassAliasPair
> ClassAliases
;
384 /// Function used for throwing Objective-C exceptions.
385 LazyRuntimeFunction ExceptionThrowFn
;
386 /// Function used for rethrowing exceptions, used at the end of \@finally or
387 /// \@synchronize blocks.
388 LazyRuntimeFunction ExceptionReThrowFn
;
389 /// Function called when entering a catch function. This is required for
390 /// differentiating Objective-C exceptions and foreign exceptions.
391 LazyRuntimeFunction EnterCatchFn
;
392 /// Function called when exiting from a catch block. Used to do exception
394 LazyRuntimeFunction ExitCatchFn
;
395 /// Function called when entering an \@synchronize block. Acquires the lock.
396 LazyRuntimeFunction SyncEnterFn
;
397 /// Function called when exiting an \@synchronize block. Releases the lock.
398 LazyRuntimeFunction SyncExitFn
;
401 /// Function called if fast enumeration detects that the collection is
402 /// modified during the update.
403 LazyRuntimeFunction EnumerationMutationFn
;
404 /// Function for implementing synthesized property getters that return an
406 LazyRuntimeFunction GetPropertyFn
;
407 /// Function for implementing synthesized property setters that return an
409 LazyRuntimeFunction SetPropertyFn
;
410 /// Function used for non-object declared property getters.
411 LazyRuntimeFunction GetStructPropertyFn
;
412 /// Function used for non-object declared property setters.
413 LazyRuntimeFunction SetStructPropertyFn
;
416 /// The version of the runtime that this class targets. Must match the
417 /// version in the runtime.
419 /// The version of the protocol class. Used to differentiate between ObjC1
420 /// and ObjC2 protocols. Objective-C 1 protocols can not contain optional
421 /// components and can not contain declared properties. We always emit
422 /// Objective-C 2 property structures, but we have to pretend that they're
423 /// Objective-C 1 property structures when targeting the GCC runtime or it
425 const int ProtocolVersion
;
426 /// The version of the class ABI. This value is used in the class structure
427 /// and indicates how various fields should be interpreted.
428 const int ClassABIVersion
;
429 /// Generates an instance variable list structure. This is a structure
430 /// containing a size and an array of structures containing instance variable
431 /// metadata. This is used purely for introspection in the fragile ABI. In
432 /// the non-fragile ABI, it's used for instance variable fixup.
433 virtual llvm::Constant
*GenerateIvarList(ArrayRef
<llvm::Constant
*> IvarNames
,
434 ArrayRef
<llvm::Constant
*> IvarTypes
,
435 ArrayRef
<llvm::Constant
*> IvarOffsets
,
436 ArrayRef
<llvm::Constant
*> IvarAlign
,
437 ArrayRef
<Qualifiers::ObjCLifetime
> IvarOwnership
);
439 /// Generates a method list structure. This is a structure containing a size
440 /// and an array of structures containing method metadata.
442 /// This structure is used by both classes and categories, and contains a next
443 /// pointer allowing them to be chained together in a linked list.
444 llvm::Constant
*GenerateMethodList(StringRef ClassName
,
445 StringRef CategoryName
,
446 ArrayRef
<const ObjCMethodDecl
*> Methods
,
447 bool isClassMethodList
);
449 /// Emits an empty protocol. This is used for \@protocol() where no protocol
450 /// is found. The runtime will (hopefully) fix up the pointer to refer to the
452 virtual llvm::Constant
*GenerateEmptyProtocol(StringRef ProtocolName
);
454 /// Generates a list of property metadata structures. This follows the same
455 /// pattern as method and instance variable metadata lists.
456 llvm::Constant
*GeneratePropertyList(const Decl
*Container
,
457 const ObjCContainerDecl
*OCD
,
458 bool isClassProperty
=false,
459 bool protocolOptionalProperties
=false);
461 /// Generates a list of referenced protocols. Classes, categories, and
462 /// protocols all use this structure.
463 llvm::Constant
*GenerateProtocolList(ArrayRef
<std::string
> Protocols
);
465 /// To ensure that all protocols are seen by the runtime, we add a category on
466 /// a class defined in the runtime, declaring no methods, but adopting the
467 /// protocols. This is a horribly ugly hack, but it allows us to collect all
468 /// of the protocols without changing the ABI.
469 void GenerateProtocolHolderCategory();
471 /// Generates a class structure.
472 llvm::Constant
*GenerateClassStructure(
473 llvm::Constant
*MetaClass
,
474 llvm::Constant
*SuperClass
,
477 llvm::Constant
*Version
,
478 llvm::Constant
*InstanceSize
,
479 llvm::Constant
*IVars
,
480 llvm::Constant
*Methods
,
481 llvm::Constant
*Protocols
,
482 llvm::Constant
*IvarOffsets
,
483 llvm::Constant
*Properties
,
484 llvm::Constant
*StrongIvarBitmap
,
485 llvm::Constant
*WeakIvarBitmap
,
488 /// Generates a method list. This is used by protocols to define the required
489 /// and optional methods.
490 virtual llvm::Constant
*GenerateProtocolMethodList(
491 ArrayRef
<const ObjCMethodDecl
*> Methods
);
492 /// Emits optional and required method lists.
494 void EmitProtocolMethodList(T
&&Methods
, llvm::Constant
*&Required
,
495 llvm::Constant
*&Optional
) {
496 SmallVector
<const ObjCMethodDecl
*, 16> RequiredMethods
;
497 SmallVector
<const ObjCMethodDecl
*, 16> OptionalMethods
;
498 for (const auto *I
: Methods
)
500 OptionalMethods
.push_back(I
);
502 RequiredMethods
.push_back(I
);
503 Required
= GenerateProtocolMethodList(RequiredMethods
);
504 Optional
= GenerateProtocolMethodList(OptionalMethods
);
507 /// Returns a selector with the specified type encoding. An empty string is
508 /// used to return an untyped selector (with the types field set to NULL).
509 virtual llvm::Value
*GetTypedSelector(CodeGenFunction
&CGF
, Selector Sel
,
510 const std::string
&TypeEncoding
);
512 /// Returns the name of ivar offset variables. In the GNUstep v1 ABI, this
513 /// contains the class and ivar names, in the v2 ABI this contains the type
514 /// encoding as well.
515 virtual std::string
GetIVarOffsetVariableName(const ObjCInterfaceDecl
*ID
,
516 const ObjCIvarDecl
*Ivar
) {
517 const std::string Name
= "__objc_ivar_offset_" + ID
->getNameAsString()
518 + '.' + Ivar
->getNameAsString();
521 /// Returns the variable used to store the offset of an instance variable.
522 llvm::GlobalVariable
*ObjCIvarOffsetVariable(const ObjCInterfaceDecl
*ID
,
523 const ObjCIvarDecl
*Ivar
);
524 /// Emits a reference to a class. This allows the linker to object if there
525 /// is no class of the matching name.
526 void EmitClassRef(const std::string
&className
);
528 /// Emits a pointer to the named class
529 virtual llvm::Value
*GetClassNamed(CodeGenFunction
&CGF
,
530 const std::string
&Name
, bool isWeak
);
532 /// Looks up the method for sending a message to the specified object. This
533 /// mechanism differs between the GCC and GNU runtimes, so this method must be
534 /// overridden in subclasses.
535 virtual llvm::Value
*LookupIMP(CodeGenFunction
&CGF
,
536 llvm::Value
*&Receiver
,
539 MessageSendInfo
&MSI
) = 0;
541 /// Looks up the method for sending a message to a superclass. This
542 /// mechanism differs between the GCC and GNU runtimes, so this method must
543 /// be overridden in subclasses.
544 virtual llvm::Value
*LookupIMPSuper(CodeGenFunction
&CGF
,
547 MessageSendInfo
&MSI
) = 0;
549 /// Libobjc2 uses a bitfield representation where small(ish) bitfields are
550 /// stored in a 64-bit value with the low bit set to 1 and the remaining 63
551 /// bits set to their values, LSB first, while larger ones are stored in a
552 /// structure of this / form:
554 /// struct { int32_t length; int32_t values[length]; };
556 /// The values in the array are stored in host-endian format, with the least
557 /// significant bit being assumed to come first in the bitfield. Therefore,
558 /// a bitfield with the 64th bit set will be (int64_t)&{ 2, [0, 1<<31] },
559 /// while a bitfield / with the 63rd bit set will be 1<<64.
560 llvm::Constant
*MakeBitField(ArrayRef
<bool> bits
);
563 CGObjCGNU(CodeGenModule
&cgm
, unsigned runtimeABIVersion
,
564 unsigned protocolClassVersion
, unsigned classABI
=1);
566 ConstantAddress
GenerateConstantString(const StringLiteral
*) override
;
569 GenerateMessageSend(CodeGenFunction
&CGF
, ReturnValueSlot Return
,
570 QualType ResultType
, Selector Sel
,
571 llvm::Value
*Receiver
, const CallArgList
&CallArgs
,
572 const ObjCInterfaceDecl
*Class
,
573 const ObjCMethodDecl
*Method
) override
;
575 GenerateMessageSendSuper(CodeGenFunction
&CGF
, ReturnValueSlot Return
,
576 QualType ResultType
, Selector Sel
,
577 const ObjCInterfaceDecl
*Class
,
578 bool isCategoryImpl
, llvm::Value
*Receiver
,
579 bool IsClassMessage
, const CallArgList
&CallArgs
,
580 const ObjCMethodDecl
*Method
) override
;
581 llvm::Value
*GetClass(CodeGenFunction
&CGF
,
582 const ObjCInterfaceDecl
*OID
) override
;
583 llvm::Value
*GetSelector(CodeGenFunction
&CGF
, Selector Sel
) override
;
584 Address
GetAddrOfSelector(CodeGenFunction
&CGF
, Selector Sel
) override
;
585 llvm::Value
*GetSelector(CodeGenFunction
&CGF
,
586 const ObjCMethodDecl
*Method
) override
;
587 virtual llvm::Constant
*GetConstantSelector(Selector Sel
,
588 const std::string
&TypeEncoding
) {
589 llvm_unreachable("Runtime unable to generate constant selector");
591 llvm::Constant
*GetConstantSelector(const ObjCMethodDecl
*M
) {
592 return GetConstantSelector(M
->getSelector(),
593 CGM
.getContext().getObjCEncodingForMethodDecl(M
));
595 llvm::Constant
*GetEHType(QualType T
) override
;
597 llvm::Function
*GenerateMethod(const ObjCMethodDecl
*OMD
,
598 const ObjCContainerDecl
*CD
) override
;
600 // Map to unify direct method definitions.
601 llvm::DenseMap
<const ObjCMethodDecl
*, llvm::Function
*>
602 DirectMethodDefinitions
;
603 void GenerateDirectMethodPrologue(CodeGenFunction
&CGF
, llvm::Function
*Fn
,
604 const ObjCMethodDecl
*OMD
,
605 const ObjCContainerDecl
*CD
) override
;
606 void GenerateCategory(const ObjCCategoryImplDecl
*CMD
) override
;
607 void GenerateClass(const ObjCImplementationDecl
*ClassDecl
) override
;
608 void RegisterAlias(const ObjCCompatibleAliasDecl
*OAD
) override
;
609 llvm::Value
*GenerateProtocolRef(CodeGenFunction
&CGF
,
610 const ObjCProtocolDecl
*PD
) override
;
611 void GenerateProtocol(const ObjCProtocolDecl
*PD
) override
;
613 virtual llvm::Constant
*GenerateProtocolRef(const ObjCProtocolDecl
*PD
);
615 llvm::Constant
*GetOrEmitProtocol(const ObjCProtocolDecl
*PD
) override
{
616 return GenerateProtocolRef(PD
);
619 llvm::Function
*ModuleInitFunction() override
;
620 llvm::FunctionCallee
GetPropertyGetFunction() override
;
621 llvm::FunctionCallee
GetPropertySetFunction() override
;
622 llvm::FunctionCallee
GetOptimizedPropertySetFunction(bool atomic
,
624 llvm::FunctionCallee
GetSetStructFunction() override
;
625 llvm::FunctionCallee
GetGetStructFunction() override
;
626 llvm::FunctionCallee
GetCppAtomicObjectGetFunction() override
;
627 llvm::FunctionCallee
GetCppAtomicObjectSetFunction() override
;
628 llvm::FunctionCallee
EnumerationMutationFunction() override
;
630 void EmitTryStmt(CodeGenFunction
&CGF
,
631 const ObjCAtTryStmt
&S
) override
;
632 void EmitSynchronizedStmt(CodeGenFunction
&CGF
,
633 const ObjCAtSynchronizedStmt
&S
) override
;
634 void EmitThrowStmt(CodeGenFunction
&CGF
,
635 const ObjCAtThrowStmt
&S
,
636 bool ClearInsertionPoint
=true) override
;
637 llvm::Value
* EmitObjCWeakRead(CodeGenFunction
&CGF
,
638 Address AddrWeakObj
) override
;
639 void EmitObjCWeakAssign(CodeGenFunction
&CGF
,
640 llvm::Value
*src
, Address dst
) override
;
641 void EmitObjCGlobalAssign(CodeGenFunction
&CGF
,
642 llvm::Value
*src
, Address dest
,
643 bool threadlocal
=false) override
;
644 void EmitObjCIvarAssign(CodeGenFunction
&CGF
, llvm::Value
*src
,
645 Address dest
, llvm::Value
*ivarOffset
) override
;
646 void EmitObjCStrongCastAssign(CodeGenFunction
&CGF
,
647 llvm::Value
*src
, Address dest
) override
;
648 void EmitGCMemmoveCollectable(CodeGenFunction
&CGF
, Address DestPtr
,
650 llvm::Value
*Size
) override
;
651 LValue
EmitObjCValueForIvar(CodeGenFunction
&CGF
, QualType ObjectTy
,
652 llvm::Value
*BaseValue
, const ObjCIvarDecl
*Ivar
,
653 unsigned CVRQualifiers
) override
;
654 llvm::Value
*EmitIvarOffset(CodeGenFunction
&CGF
,
655 const ObjCInterfaceDecl
*Interface
,
656 const ObjCIvarDecl
*Ivar
) override
;
657 llvm::Value
*EmitNSAutoreleasePoolClassRef(CodeGenFunction
&CGF
) override
;
658 llvm::Constant
*BuildGCBlockLayout(CodeGenModule
&CGM
,
659 const CGBlockInfo
&blockInfo
) override
{
662 llvm::Constant
*BuildRCBlockLayout(CodeGenModule
&CGM
,
663 const CGBlockInfo
&blockInfo
) override
{
667 llvm::Constant
*BuildByrefLayout(CodeGenModule
&CGM
, QualType T
) override
{
672 /// Class representing the legacy GCC Objective-C ABI. This is the default when
673 /// -fobjc-nonfragile-abi is not specified.
675 /// The GCC ABI target actually generates code that is approximately compatible
676 /// with the new GNUstep runtime ABI, but refrains from using any features that
677 /// would not work with the GCC runtime. For example, clang always generates
678 /// the extended form of the class structure, and the extra fields are simply
679 /// ignored by GCC libobjc.
680 class CGObjCGCC
: public CGObjCGNU
{
681 /// The GCC ABI message lookup function. Returns an IMP pointing to the
682 /// method implementation for this message.
683 LazyRuntimeFunction MsgLookupFn
;
684 /// The GCC ABI superclass message lookup function. Takes a pointer to a
685 /// structure describing the receiver and the class, and a selector as
686 /// arguments. Returns the IMP for the corresponding method.
687 LazyRuntimeFunction MsgLookupSuperFn
;
690 llvm::Value
*LookupIMP(CodeGenFunction
&CGF
, llvm::Value
*&Receiver
,
691 llvm::Value
*cmd
, llvm::MDNode
*node
,
692 MessageSendInfo
&MSI
) override
{
693 CGBuilderTy
&Builder
= CGF
.Builder
;
694 llvm::Value
*args
[] = {
695 EnforceType(Builder
, Receiver
, IdTy
),
696 EnforceType(Builder
, cmd
, SelectorTy
) };
697 llvm::CallBase
*imp
= CGF
.EmitRuntimeCallOrInvoke(MsgLookupFn
, args
);
698 imp
->setMetadata(msgSendMDKind
, node
);
702 llvm::Value
*LookupIMPSuper(CodeGenFunction
&CGF
, Address ObjCSuper
,
703 llvm::Value
*cmd
, MessageSendInfo
&MSI
) override
{
704 CGBuilderTy
&Builder
= CGF
.Builder
;
705 llvm::Value
*lookupArgs
[] = {
706 EnforceType(Builder
, ObjCSuper
.emitRawPointer(CGF
), PtrToObjCSuperTy
),
708 return CGF
.EmitNounwindRuntimeCall(MsgLookupSuperFn
, lookupArgs
);
712 CGObjCGCC(CodeGenModule
&Mod
) : CGObjCGNU(Mod
, 8, 2) {
713 // IMP objc_msg_lookup(id, SEL);
714 MsgLookupFn
.init(&CGM
, "objc_msg_lookup", IMPTy
, IdTy
, SelectorTy
);
715 // IMP objc_msg_lookup_super(struct objc_super*, SEL);
716 MsgLookupSuperFn
.init(&CGM
, "objc_msg_lookup_super", IMPTy
,
717 PtrToObjCSuperTy
, SelectorTy
);
721 /// Class used when targeting the new GNUstep runtime ABI.
722 class CGObjCGNUstep
: public CGObjCGNU
{
723 /// The slot lookup function. Returns a pointer to a cacheable structure
724 /// that contains (among other things) the IMP.
725 LazyRuntimeFunction SlotLookupFn
;
726 /// The GNUstep ABI superclass message lookup function. Takes a pointer to
727 /// a structure describing the receiver and the class, and a selector as
728 /// arguments. Returns the slot for the corresponding method. Superclass
729 /// message lookup rarely changes, so this is a good caching opportunity.
730 LazyRuntimeFunction SlotLookupSuperFn
;
731 /// Specialised function for setting atomic retain properties
732 LazyRuntimeFunction SetPropertyAtomic
;
733 /// Specialised function for setting atomic copy properties
734 LazyRuntimeFunction SetPropertyAtomicCopy
;
735 /// Specialised function for setting nonatomic retain properties
736 LazyRuntimeFunction SetPropertyNonAtomic
;
737 /// Specialised function for setting nonatomic copy properties
738 LazyRuntimeFunction SetPropertyNonAtomicCopy
;
739 /// Function to perform atomic copies of C++ objects with nontrivial copy
740 /// constructors from Objective-C ivars.
741 LazyRuntimeFunction CxxAtomicObjectGetFn
;
742 /// Function to perform atomic copies of C++ objects with nontrivial copy
743 /// constructors to Objective-C ivars.
744 LazyRuntimeFunction CxxAtomicObjectSetFn
;
745 /// Type of a slot structure pointer. This is returned by the various
746 /// lookup functions.
748 /// Type of a slot structure.
749 llvm::Type
*SlotStructTy
;
752 llvm::Constant
*GetEHType(QualType T
) override
;
755 llvm::Value
*LookupIMP(CodeGenFunction
&CGF
, llvm::Value
*&Receiver
,
756 llvm::Value
*cmd
, llvm::MDNode
*node
,
757 MessageSendInfo
&MSI
) override
{
758 CGBuilderTy
&Builder
= CGF
.Builder
;
759 llvm::FunctionCallee LookupFn
= SlotLookupFn
;
761 // Store the receiver on the stack so that we can reload it later
762 RawAddress ReceiverPtr
=
763 CGF
.CreateTempAlloca(Receiver
->getType(), CGF
.getPointerAlign());
764 Builder
.CreateStore(Receiver
, ReceiverPtr
);
768 if (isa
<ObjCMethodDecl
>(CGF
.CurCodeDecl
)) {
769 self
= CGF
.LoadObjCSelf();
771 self
= llvm::ConstantPointerNull::get(IdTy
);
774 // The lookup function is guaranteed not to capture the receiver pointer.
775 if (auto *LookupFn2
= dyn_cast
<llvm::Function
>(LookupFn
.getCallee()))
776 LookupFn2
->addParamAttr(0, llvm::Attribute::NoCapture
);
778 llvm::Value
*args
[] = {
779 EnforceType(Builder
, ReceiverPtr
.getPointer(), PtrToIdTy
),
780 EnforceType(Builder
, cmd
, SelectorTy
),
781 EnforceType(Builder
, self
, IdTy
)};
782 llvm::CallBase
*slot
= CGF
.EmitRuntimeCallOrInvoke(LookupFn
, args
);
783 slot
->setOnlyReadsMemory();
784 slot
->setMetadata(msgSendMDKind
, node
);
786 // Load the imp from the slot
787 llvm::Value
*imp
= Builder
.CreateAlignedLoad(
788 IMPTy
, Builder
.CreateStructGEP(SlotStructTy
, slot
, 4),
789 CGF
.getPointerAlign());
791 // The lookup function may have changed the receiver, so make sure we use
793 Receiver
= Builder
.CreateLoad(ReceiverPtr
, true);
797 llvm::Value
*LookupIMPSuper(CodeGenFunction
&CGF
, Address ObjCSuper
,
799 MessageSendInfo
&MSI
) override
{
800 CGBuilderTy
&Builder
= CGF
.Builder
;
801 llvm::Value
*lookupArgs
[] = {ObjCSuper
.emitRawPointer(CGF
), cmd
};
803 llvm::CallInst
*slot
=
804 CGF
.EmitNounwindRuntimeCall(SlotLookupSuperFn
, lookupArgs
);
805 slot
->setOnlyReadsMemory();
807 return Builder
.CreateAlignedLoad(
808 IMPTy
, Builder
.CreateStructGEP(SlotStructTy
, slot
, 4),
809 CGF
.getPointerAlign());
813 CGObjCGNUstep(CodeGenModule
&Mod
) : CGObjCGNUstep(Mod
, 9, 3, 1) {}
814 CGObjCGNUstep(CodeGenModule
&Mod
, unsigned ABI
, unsigned ProtocolABI
,
816 CGObjCGNU(Mod
, ABI
, ProtocolABI
, ClassABI
) {
817 const ObjCRuntime
&R
= CGM
.getLangOpts().ObjCRuntime
;
819 SlotStructTy
= llvm::StructType::get(PtrTy
, PtrTy
, PtrTy
, IntTy
, IMPTy
);
820 SlotTy
= llvm::PointerType::getUnqual(SlotStructTy
);
821 // Slot_t objc_msg_lookup_sender(id *receiver, SEL selector, id sender);
822 SlotLookupFn
.init(&CGM
, "objc_msg_lookup_sender", SlotTy
, PtrToIdTy
,
824 // Slot_t objc_slot_lookup_super(struct objc_super*, SEL);
825 SlotLookupSuperFn
.init(&CGM
, "objc_slot_lookup_super", SlotTy
,
826 PtrToObjCSuperTy
, SelectorTy
);
827 // If we're in ObjC++ mode, then we want to make
828 llvm::Type
*VoidTy
= llvm::Type::getVoidTy(VMContext
);
829 if (usesCxxExceptions
) {
830 // void *__cxa_begin_catch(void *e)
831 EnterCatchFn
.init(&CGM
, "__cxa_begin_catch", PtrTy
, PtrTy
);
832 // void __cxa_end_catch(void)
833 ExitCatchFn
.init(&CGM
, "__cxa_end_catch", VoidTy
);
834 // void objc_exception_rethrow(void*)
835 ExceptionReThrowFn
.init(&CGM
, "__cxa_rethrow", PtrTy
);
836 } else if (usesSEHExceptions
) {
837 // void objc_exception_rethrow(void)
838 ExceptionReThrowFn
.init(&CGM
, "objc_exception_rethrow", VoidTy
);
839 } else if (CGM
.getLangOpts().CPlusPlus
) {
840 // void *__cxa_begin_catch(void *e)
841 EnterCatchFn
.init(&CGM
, "__cxa_begin_catch", PtrTy
, PtrTy
);
842 // void __cxa_end_catch(void)
843 ExitCatchFn
.init(&CGM
, "__cxa_end_catch", VoidTy
);
844 // void _Unwind_Resume_or_Rethrow(void*)
845 ExceptionReThrowFn
.init(&CGM
, "_Unwind_Resume_or_Rethrow", VoidTy
,
847 } else if (R
.getVersion() >= VersionTuple(1, 7)) {
848 // id objc_begin_catch(void *e)
849 EnterCatchFn
.init(&CGM
, "objc_begin_catch", IdTy
, PtrTy
);
850 // void objc_end_catch(void)
851 ExitCatchFn
.init(&CGM
, "objc_end_catch", VoidTy
);
852 // void _Unwind_Resume_or_Rethrow(void*)
853 ExceptionReThrowFn
.init(&CGM
, "objc_exception_rethrow", VoidTy
, PtrTy
);
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 /// The subset of `objc_class_flags` used at compile time.
926 /// This is a metaclass
927 ClassFlagMeta
= (1 << 0),
928 /// This class has been initialised by the runtime (+initialize has been
929 /// sent if necessary).
930 ClassFlagInitialized
= (1 << 8),
932 static const char *const SectionsBaseNames
[8];
933 static const char *const PECOFFSectionsBaseNames
[8];
934 template<SectionKind K
>
935 std::string
sectionName() {
936 if (CGM
.getTriple().isOSBinFormatCOFF()) {
937 std::string
name(PECOFFSectionsBaseNames
[K
]);
941 return SectionsBaseNames
[K
];
943 /// The GCC ABI superclass message lookup function. Takes a pointer to a
944 /// structure describing the receiver and the class, and a selector as
945 /// arguments. Returns the IMP for the corresponding method.
946 LazyRuntimeFunction MsgLookupSuperFn
;
947 /// Function to ensure that +initialize is sent to a class.
948 LazyRuntimeFunction SentInitializeFn
;
949 /// A flag indicating if we've emitted at least one protocol.
950 /// If we haven't, then we need to emit an empty protocol, to ensure that the
951 /// __start__objc_protocols and __stop__objc_protocols sections exist.
952 bool EmittedProtocol
= false;
953 /// A flag indicating if we've emitted at least one protocol reference.
954 /// If we haven't, then we need to emit an empty protocol, to ensure that the
955 /// __start__objc_protocol_refs and __stop__objc_protocol_refs sections
957 bool EmittedProtocolRef
= false;
958 /// A flag indicating if we've emitted at least one class.
959 /// If we haven't, then we need to emit an empty protocol, to ensure that the
960 /// __start__objc_classes and __stop__objc_classes sections / exist.
961 bool EmittedClass
= false;
962 /// Generate the name of a symbol for a reference to a class. Accesses to
963 /// classes should be indirected via this.
965 typedef std::pair
<std::string
, std::pair
<llvm::GlobalVariable
*, int>>
967 std::vector
<EarlyInitPair
> EarlyInitList
;
969 std::string
SymbolForClassRef(StringRef Name
, bool isWeak
) {
971 return (ManglePublicSymbol("OBJC_WEAK_REF_CLASS_") + Name
).str();
973 return (ManglePublicSymbol("OBJC_REF_CLASS_") + Name
).str();
975 /// Generate the name of a class symbol.
976 std::string
SymbolForClass(StringRef Name
) {
977 return (ManglePublicSymbol("OBJC_CLASS_") + Name
).str();
979 void CallRuntimeFunction(CGBuilderTy
&B
, StringRef FunctionName
,
980 ArrayRef
<llvm::Value
*> Args
) {
981 SmallVector
<llvm::Type
*,8> Types
;
982 for (auto *Arg
: Args
)
983 Types
.push_back(Arg
->getType());
984 llvm::FunctionType
*FT
= llvm::FunctionType::get(B
.getVoidTy(), Types
,
986 llvm::FunctionCallee Fn
= CGM
.CreateRuntimeFunction(FT
, FunctionName
);
987 B
.CreateCall(Fn
, Args
);
990 ConstantAddress
GenerateConstantString(const StringLiteral
*SL
) override
{
992 auto Str
= SL
->getString();
993 CharUnits Align
= CGM
.getPointerAlign();
995 // Look for an existing one
996 llvm::StringMap
<llvm::Constant
*>::iterator old
= ObjCStrings
.find(Str
);
997 if (old
!= ObjCStrings
.end())
998 return ConstantAddress(old
->getValue(), IdElemTy
, Align
);
1000 bool isNonASCII
= SL
->containsNonAscii();
1002 auto LiteralLength
= SL
->getLength();
1004 if ((CGM
.getTarget().getPointerWidth(LangAS::Default
) == 64) &&
1005 (LiteralLength
< 9) && !isNonASCII
) {
1006 // Tiny strings are only used on 64-bit platforms. They store 8 7-bit
1007 // ASCII characters in the high 56 bits, followed by a 4-bit length and a
1008 // 3-bit tag (which is always 4).
1010 // Fill in the characters
1011 for (unsigned i
=0 ; i
<LiteralLength
; i
++)
1012 str
|= ((uint64_t)SL
->getCodeUnit(i
)) << ((64 - 4 - 3) - (i
*7));
1013 // Fill in the length
1014 str
|= LiteralLength
<< 3;
1017 auto *ObjCStr
= llvm::ConstantExpr::getIntToPtr(
1018 llvm::ConstantInt::get(Int64Ty
, str
), IdTy
);
1019 ObjCStrings
[Str
] = ObjCStr
;
1020 return ConstantAddress(ObjCStr
, IdElemTy
, Align
);
1023 StringRef StringClass
= CGM
.getLangOpts().ObjCConstantStringClass
;
1025 if (StringClass
.empty()) StringClass
= "NSConstantString";
1027 std::string Sym
= SymbolForClass(StringClass
);
1029 llvm::Constant
*isa
= TheModule
.getNamedGlobal(Sym
);
1032 isa
= new llvm::GlobalVariable(TheModule
, IdTy
, /* isConstant */false,
1033 llvm::GlobalValue::ExternalLinkage
, nullptr, Sym
);
1034 if (CGM
.getTriple().isOSBinFormatCOFF()) {
1035 cast
<llvm::GlobalValue
>(isa
)->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass
);
1043 // uint32_t length; // Number of codepoints
1044 // uint32_t size; // Number of bytes
1046 // const char *data;
1049 ConstantInitBuilder
Builder(CGM
);
1050 auto Fields
= Builder
.beginStruct();
1051 if (!CGM
.getTriple().isOSBinFormatCOFF()) {
1054 Fields
.addNullPointer(PtrTy
);
1056 // For now, all non-ASCII strings are represented as UTF-16. As such, the
1057 // number of bytes is simply double the number of UTF-16 codepoints. In
1058 // ASCII strings, the number of bytes is equal to the number of non-ASCII
1061 unsigned NumU8CodeUnits
= Str
.size();
1062 // A UTF-16 representation of a unicode string contains at most the same
1063 // number of code units as a UTF-8 representation. Allocate that much
1064 // space, plus one for the final null character.
1065 SmallVector
<llvm::UTF16
, 128> ToBuf(NumU8CodeUnits
+ 1);
1066 const llvm::UTF8
*FromPtr
= (const llvm::UTF8
*)Str
.data();
1067 llvm::UTF16
*ToPtr
= &ToBuf
[0];
1068 (void)llvm::ConvertUTF8toUTF16(&FromPtr
, FromPtr
+ NumU8CodeUnits
,
1069 &ToPtr
, ToPtr
+ NumU8CodeUnits
, llvm::strictConversion
);
1070 uint32_t StringLength
= ToPtr
- &ToBuf
[0];
1071 // Add null terminator
1073 // Flags: 2 indicates UTF-16 encoding
1074 Fields
.addInt(Int32Ty
, 2);
1075 // Number of UTF-16 codepoints
1076 Fields
.addInt(Int32Ty
, StringLength
);
1078 Fields
.addInt(Int32Ty
, StringLength
* 2);
1079 // Hash. Not currently initialised by the compiler.
1080 Fields
.addInt(Int32Ty
, 0);
1081 // pointer to the data string.
1082 auto Arr
= llvm::ArrayRef(&ToBuf
[0], ToPtr
+ 1);
1083 auto *C
= llvm::ConstantDataArray::get(VMContext
, Arr
);
1084 auto *Buffer
= new llvm::GlobalVariable(TheModule
, C
->getType(),
1085 /*isConstant=*/true, llvm::GlobalValue::PrivateLinkage
, C
, ".str");
1086 Buffer
->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global
);
1089 // Flags: 0 indicates ASCII encoding
1090 Fields
.addInt(Int32Ty
, 0);
1091 // Number of UTF-16 codepoints, each ASCII byte is a UTF-16 codepoint
1092 Fields
.addInt(Int32Ty
, Str
.size());
1094 Fields
.addInt(Int32Ty
, Str
.size());
1095 // Hash. Not currently initialised by the compiler.
1096 Fields
.addInt(Int32Ty
, 0);
1098 Fields
.add(MakeConstantString(Str
));
1100 std::string StringName
;
1101 bool isNamed
= !isNonASCII
;
1103 StringName
= ".objc_str_";
1104 for (int i
=0,e
=Str
.size() ; i
<e
; ++i
) {
1105 unsigned char c
= Str
[i
];
1116 llvm::GlobalVariable
*ObjCStrGV
=
1117 Fields
.finishAndCreateGlobal(
1118 isNamed
? StringRef(StringName
) : ".objc_string",
1119 Align
, false, isNamed
? llvm::GlobalValue::LinkOnceODRLinkage
1120 : llvm::GlobalValue::PrivateLinkage
);
1121 ObjCStrGV
->setSection(sectionName
<ConstantStringSection
>());
1123 ObjCStrGV
->setComdat(TheModule
.getOrInsertComdat(StringName
));
1124 ObjCStrGV
->setVisibility(llvm::GlobalValue::HiddenVisibility
);
1126 if (CGM
.getTriple().isOSBinFormatCOFF()) {
1127 std::pair
<llvm::GlobalVariable
*, int> v
{ObjCStrGV
, 0};
1128 EarlyInitList
.emplace_back(Sym
, v
);
1130 ObjCStrings
[Str
] = ObjCStrGV
;
1131 ConstantStrings
.push_back(ObjCStrGV
);
1132 return ConstantAddress(ObjCStrGV
, IdElemTy
, Align
);
1135 void PushProperty(ConstantArrayBuilder
&PropertiesArray
,
1136 const ObjCPropertyDecl
*property
,
1138 bool isSynthesized
=true, bool
1139 isDynamic
=true) override
{
1140 // struct objc_property
1142 // const char *name;
1143 // const char *attributes;
1144 // const char *type;
1148 auto Fields
= PropertiesArray
.beginStruct(PropertyMetadataTy
);
1149 ASTContext
&Context
= CGM
.getContext();
1150 Fields
.add(MakeConstantString(property
->getNameAsString()));
1151 std::string TypeStr
=
1152 CGM
.getContext().getObjCEncodingForPropertyDecl(property
, OCD
);
1153 Fields
.add(MakeConstantString(TypeStr
));
1154 std::string typeStr
;
1155 Context
.getObjCEncodingForType(property
->getType(), typeStr
);
1156 Fields
.add(MakeConstantString(typeStr
));
1157 auto addPropertyMethod
= [&](const ObjCMethodDecl
*accessor
) {
1159 std::string TypeStr
= Context
.getObjCEncodingForMethodDecl(accessor
);
1160 Fields
.add(GetConstantSelector(accessor
->getSelector(), TypeStr
));
1162 Fields
.add(NULLPtr
);
1165 addPropertyMethod(property
->getGetterMethodDecl());
1166 addPropertyMethod(property
->getSetterMethodDecl());
1167 Fields
.finishAndAddTo(PropertiesArray
);
1171 GenerateProtocolMethodList(ArrayRef
<const ObjCMethodDecl
*> Methods
) override
{
1172 // struct objc_protocol_method_description
1175 // const char *types;
1177 llvm::StructType
*ObjCMethodDescTy
=
1178 llvm::StructType::get(CGM
.getLLVMContext(),
1179 { PtrToInt8Ty
, PtrToInt8Ty
});
1180 ASTContext
&Context
= CGM
.getContext();
1181 ConstantInitBuilder
Builder(CGM
);
1182 // struct objc_protocol_method_description_list
1186 // struct objc_protocol_method_description methods[];
1188 auto MethodList
= Builder
.beginStruct();
1190 MethodList
.addInt(IntTy
, Methods
.size());
1191 // int size; // sizeof(struct objc_method_description)
1192 const llvm::DataLayout
&DL
= TheModule
.getDataLayout();
1193 MethodList
.addInt(IntTy
, DL
.getTypeSizeInBits(ObjCMethodDescTy
) /
1194 CGM
.getContext().getCharWidth());
1195 // struct objc_method_description[]
1196 auto MethodArray
= MethodList
.beginArray(ObjCMethodDescTy
);
1197 for (auto *M
: Methods
) {
1198 auto Method
= MethodArray
.beginStruct(ObjCMethodDescTy
);
1199 Method
.add(CGObjCGNU::GetConstantSelector(M
));
1200 Method
.add(GetTypeString(Context
.getObjCEncodingForMethodDecl(M
, true)));
1201 Method
.finishAndAddTo(MethodArray
);
1203 MethodArray
.finishAndAddTo(MethodList
);
1204 return MethodList
.finishAndCreateGlobal(".objc_protocol_method_list",
1205 CGM
.getPointerAlign());
1207 llvm::Constant
*GenerateCategoryProtocolList(const ObjCCategoryDecl
*OCD
)
1209 const auto &ReferencedProtocols
= OCD
->getReferencedProtocols();
1210 auto RuntimeProtocols
= GetRuntimeProtocolList(ReferencedProtocols
.begin(),
1211 ReferencedProtocols
.end());
1212 SmallVector
<llvm::Constant
*, 16> Protocols
;
1213 for (const auto *PI
: RuntimeProtocols
)
1214 Protocols
.push_back(GenerateProtocolRef(PI
));
1215 return GenerateProtocolList(Protocols
);
1218 llvm::Value
*LookupIMPSuper(CodeGenFunction
&CGF
, Address ObjCSuper
,
1219 llvm::Value
*cmd
, MessageSendInfo
&MSI
) override
{
1220 // Don't access the slot unless we're trying to cache the result.
1221 CGBuilderTy
&Builder
= CGF
.Builder
;
1222 llvm::Value
*lookupArgs
[] = {
1223 CGObjCGNU::EnforceType(Builder
, ObjCSuper
.emitRawPointer(CGF
),
1226 return CGF
.EmitNounwindRuntimeCall(MsgLookupSuperFn
, lookupArgs
);
1229 llvm::GlobalVariable
*GetClassVar(StringRef Name
, bool isWeak
=false) {
1230 std::string SymbolName
= SymbolForClassRef(Name
, isWeak
);
1231 auto *ClassSymbol
= TheModule
.getNamedGlobal(SymbolName
);
1234 ClassSymbol
= new llvm::GlobalVariable(TheModule
,
1235 IdTy
, false, llvm::GlobalValue::ExternalLinkage
,
1236 nullptr, SymbolName
);
1237 // If this is a weak symbol, then we are creating a valid definition for
1238 // the symbol, pointing to a weak definition of the real class pointer. If
1239 // this is not a weak reference, then we are expecting another compilation
1240 // unit to provide the real indirection symbol.
1242 ClassSymbol
->setInitializer(new llvm::GlobalVariable(TheModule
,
1243 Int8Ty
, false, llvm::GlobalValue::ExternalWeakLinkage
,
1244 nullptr, SymbolForClass(Name
)));
1246 if (CGM
.getTriple().isOSBinFormatCOFF()) {
1247 IdentifierInfo
&II
= CGM
.getContext().Idents
.get(Name
);
1248 TranslationUnitDecl
*TUDecl
= CGM
.getContext().getTranslationUnitDecl();
1249 DeclContext
*DC
= TranslationUnitDecl::castToDeclContext(TUDecl
);
1251 const ObjCInterfaceDecl
*OID
= nullptr;
1252 for (const auto *Result
: DC
->lookup(&II
))
1253 if ((OID
= dyn_cast
<ObjCInterfaceDecl
>(Result
)))
1256 // The first Interface we find may be a @class,
1257 // which should only be treated as the source of
1258 // truth in the absence of a true declaration.
1259 assert(OID
&& "Failed to find ObjCInterfaceDecl");
1260 const ObjCInterfaceDecl
*OIDDef
= OID
->getDefinition();
1261 if (OIDDef
!= nullptr)
1264 auto Storage
= llvm::GlobalValue::DefaultStorageClass
;
1265 if (OID
->hasAttr
<DLLImportAttr
>())
1266 Storage
= llvm::GlobalValue::DLLImportStorageClass
;
1267 else if (OID
->hasAttr
<DLLExportAttr
>())
1268 Storage
= llvm::GlobalValue::DLLExportStorageClass
;
1270 cast
<llvm::GlobalValue
>(ClassSymbol
)->setDLLStorageClass(Storage
);
1273 assert(ClassSymbol
->getName() == SymbolName
);
1276 llvm::Value
*GetClassNamed(CodeGenFunction
&CGF
,
1277 const std::string
&Name
,
1278 bool isWeak
) override
{
1279 return CGF
.Builder
.CreateLoad(
1280 Address(GetClassVar(Name
, isWeak
), IdTy
, CGM
.getPointerAlign()));
1282 int32_t FlagsForOwnership(Qualifiers::ObjCLifetime Ownership
) {
1284 // ownership_invalid = 0,
1285 // ownership_strong = 1,
1286 // ownership_weak = 2,
1287 // ownership_unsafe = 3
1288 // } ivar_ownership;
1290 switch (Ownership
) {
1291 case Qualifiers::OCL_Strong
:
1294 case Qualifiers::OCL_Weak
:
1297 case Qualifiers::OCL_ExplicitNone
:
1300 case Qualifiers::OCL_None
:
1301 case Qualifiers::OCL_Autoreleasing
:
1302 assert(Ownership
!= Qualifiers::OCL_Autoreleasing
);
1307 llvm::Constant
*GenerateIvarList(ArrayRef
<llvm::Constant
*> IvarNames
,
1308 ArrayRef
<llvm::Constant
*> IvarTypes
,
1309 ArrayRef
<llvm::Constant
*> IvarOffsets
,
1310 ArrayRef
<llvm::Constant
*> IvarAlign
,
1311 ArrayRef
<Qualifiers::ObjCLifetime
> IvarOwnership
) override
{
1312 llvm_unreachable("Method should not be called!");
1315 llvm::Constant
*GenerateEmptyProtocol(StringRef ProtocolName
) override
{
1316 std::string Name
= SymbolForProtocol(ProtocolName
);
1317 auto *GV
= TheModule
.getGlobalVariable(Name
);
1319 // Emit a placeholder symbol.
1320 GV
= new llvm::GlobalVariable(TheModule
, ProtocolTy
, false,
1321 llvm::GlobalValue::ExternalLinkage
, nullptr, Name
);
1322 GV
->setAlignment(CGM
.getPointerAlign().getAsAlign());
1327 /// Existing protocol references.
1328 llvm::StringMap
<llvm::Constant
*> ExistingProtocolRefs
;
1330 llvm::Value
*GenerateProtocolRef(CodeGenFunction
&CGF
,
1331 const ObjCProtocolDecl
*PD
) override
{
1332 auto Name
= PD
->getNameAsString();
1333 auto *&Ref
= ExistingProtocolRefs
[Name
];
1335 auto *&Protocol
= ExistingProtocols
[Name
];
1337 Protocol
= GenerateProtocolRef(PD
);
1338 std::string RefName
= SymbolForProtocolRef(Name
);
1339 assert(!TheModule
.getGlobalVariable(RefName
));
1340 // Emit a reference symbol.
1341 auto GV
= new llvm::GlobalVariable(TheModule
, ProtocolPtrTy
, false,
1342 llvm::GlobalValue::LinkOnceODRLinkage
,
1344 GV
->setComdat(TheModule
.getOrInsertComdat(RefName
));
1345 GV
->setSection(sectionName
<ProtocolReferenceSection
>());
1346 GV
->setAlignment(CGM
.getPointerAlign().getAsAlign());
1349 EmittedProtocolRef
= true;
1350 return CGF
.Builder
.CreateAlignedLoad(ProtocolPtrTy
, Ref
,
1351 CGM
.getPointerAlign());
1354 llvm::Constant
*GenerateProtocolList(ArrayRef
<llvm::Constant
*> Protocols
) {
1355 llvm::ArrayType
*ProtocolArrayTy
= llvm::ArrayType::get(ProtocolPtrTy
,
1357 llvm::Constant
* ProtocolArray
= llvm::ConstantArray::get(ProtocolArrayTy
,
1359 ConstantInitBuilder
builder(CGM
);
1360 auto ProtocolBuilder
= builder
.beginStruct();
1361 ProtocolBuilder
.addNullPointer(PtrTy
);
1362 ProtocolBuilder
.addInt(SizeTy
, Protocols
.size());
1363 ProtocolBuilder
.add(ProtocolArray
);
1364 return ProtocolBuilder
.finishAndCreateGlobal(".objc_protocol_list",
1365 CGM
.getPointerAlign(), false, llvm::GlobalValue::InternalLinkage
);
1368 void GenerateProtocol(const ObjCProtocolDecl
*PD
) override
{
1369 // Do nothing - we only emit referenced protocols.
1371 llvm::Constant
*GenerateProtocolRef(const ObjCProtocolDecl
*PD
) override
{
1372 std::string ProtocolName
= PD
->getNameAsString();
1373 auto *&Protocol
= ExistingProtocols
[ProtocolName
];
1377 EmittedProtocol
= true;
1379 auto SymName
= SymbolForProtocol(ProtocolName
);
1380 auto *OldGV
= TheModule
.getGlobalVariable(SymName
);
1382 // Use the protocol definition, if there is one.
1383 if (const ObjCProtocolDecl
*Def
= PD
->getDefinition())
1386 // If there is no definition, then create an external linkage symbol and
1387 // hope that someone else fills it in for us (and fail to link if they
1390 Protocol
= new llvm::GlobalVariable(TheModule
, ProtocolTy
,
1391 /*isConstant*/false,
1392 llvm::GlobalValue::ExternalLinkage
, nullptr, SymName
);
1396 SmallVector
<llvm::Constant
*, 16> Protocols
;
1397 auto RuntimeProtocols
=
1398 GetRuntimeProtocolList(PD
->protocol_begin(), PD
->protocol_end());
1399 for (const auto *PI
: RuntimeProtocols
)
1400 Protocols
.push_back(GenerateProtocolRef(PI
));
1401 llvm::Constant
*ProtocolList
= GenerateProtocolList(Protocols
);
1403 // Collect information about methods
1404 llvm::Constant
*InstanceMethodList
, *OptionalInstanceMethodList
;
1405 llvm::Constant
*ClassMethodList
, *OptionalClassMethodList
;
1406 EmitProtocolMethodList(PD
->instance_methods(), InstanceMethodList
,
1407 OptionalInstanceMethodList
);
1408 EmitProtocolMethodList(PD
->class_methods(), ClassMethodList
,
1409 OptionalClassMethodList
);
1411 // The isa pointer must be set to a magic number so the runtime knows it's
1412 // the correct layout.
1413 ConstantInitBuilder
builder(CGM
);
1414 auto ProtocolBuilder
= builder
.beginStruct();
1415 ProtocolBuilder
.add(llvm::ConstantExpr::getIntToPtr(
1416 llvm::ConstantInt::get(Int32Ty
, ProtocolVersion
), IdTy
));
1417 ProtocolBuilder
.add(MakeConstantString(ProtocolName
));
1418 ProtocolBuilder
.add(ProtocolList
);
1419 ProtocolBuilder
.add(InstanceMethodList
);
1420 ProtocolBuilder
.add(ClassMethodList
);
1421 ProtocolBuilder
.add(OptionalInstanceMethodList
);
1422 ProtocolBuilder
.add(OptionalClassMethodList
);
1423 // Required instance properties
1424 ProtocolBuilder
.add(GeneratePropertyList(nullptr, PD
, false, false));
1425 // Optional instance properties
1426 ProtocolBuilder
.add(GeneratePropertyList(nullptr, PD
, false, true));
1427 // Required class properties
1428 ProtocolBuilder
.add(GeneratePropertyList(nullptr, PD
, true, false));
1429 // Optional class properties
1430 ProtocolBuilder
.add(GeneratePropertyList(nullptr, PD
, true, true));
1432 auto *GV
= ProtocolBuilder
.finishAndCreateGlobal(SymName
,
1433 CGM
.getPointerAlign(), false, llvm::GlobalValue::ExternalLinkage
);
1434 GV
->setSection(sectionName
<ProtocolSection
>());
1435 GV
->setComdat(TheModule
.getOrInsertComdat(SymName
));
1437 OldGV
->replaceAllUsesWith(GV
);
1438 OldGV
->removeFromParent();
1439 GV
->setName(SymName
);
1444 llvm::Value
*GetTypedSelector(CodeGenFunction
&CGF
, Selector Sel
,
1445 const std::string
&TypeEncoding
) override
{
1446 return GetConstantSelector(Sel
, TypeEncoding
);
1448 std::string
GetSymbolNameForTypeEncoding(const std::string
&TypeEncoding
) {
1449 std::string MangledTypes
= std::string(TypeEncoding
);
1450 // @ is used as a special character in ELF symbol names (used for symbol
1451 // versioning), so mangle the name to not include it. Replace it with a
1452 // character that is not a valid type encoding character (and, being
1453 // non-printable, never will be!)
1454 if (CGM
.getTriple().isOSBinFormatELF())
1455 std::replace(MangledTypes
.begin(), MangledTypes
.end(), '@', '\1');
1456 // = in dll exported names causes lld to fail when linking on Windows.
1457 if (CGM
.getTriple().isOSWindows())
1458 std::replace(MangledTypes
.begin(), MangledTypes
.end(), '=', '\2');
1459 return MangledTypes
;
1461 llvm::Constant
*GetTypeString(llvm::StringRef TypeEncoding
) {
1462 if (TypeEncoding
.empty())
1464 std::string MangledTypes
=
1465 GetSymbolNameForTypeEncoding(std::string(TypeEncoding
));
1466 std::string TypesVarName
= ".objc_sel_types_" + MangledTypes
;
1467 auto *TypesGlobal
= TheModule
.getGlobalVariable(TypesVarName
);
1469 llvm::Constant
*Init
= llvm::ConstantDataArray::getString(VMContext
,
1471 auto *GV
= new llvm::GlobalVariable(TheModule
, Init
->getType(),
1472 true, llvm::GlobalValue::LinkOnceODRLinkage
, Init
, TypesVarName
);
1473 GV
->setComdat(TheModule
.getOrInsertComdat(TypesVarName
));
1474 GV
->setVisibility(llvm::GlobalValue::HiddenVisibility
);
1479 llvm::Constant
*GetConstantSelector(Selector Sel
,
1480 const std::string
&TypeEncoding
) override
{
1481 std::string MangledTypes
= GetSymbolNameForTypeEncoding(TypeEncoding
);
1482 auto SelVarName
= (StringRef(".objc_selector_") + Sel
.getAsString() + "_" +
1483 MangledTypes
).str();
1484 if (auto *GV
= TheModule
.getNamedGlobal(SelVarName
))
1486 ConstantInitBuilder
builder(CGM
);
1487 auto SelBuilder
= builder
.beginStruct();
1488 SelBuilder
.add(ExportUniqueString(Sel
.getAsString(), ".objc_sel_name_",
1490 SelBuilder
.add(GetTypeString(TypeEncoding
));
1491 auto *GV
= SelBuilder
.finishAndCreateGlobal(SelVarName
,
1492 CGM
.getPointerAlign(), false, llvm::GlobalValue::LinkOnceODRLinkage
);
1493 GV
->setComdat(TheModule
.getOrInsertComdat(SelVarName
));
1494 GV
->setVisibility(llvm::GlobalValue::HiddenVisibility
);
1495 GV
->setSection(sectionName
<SelectorSection
>());
1498 llvm::StructType
*emptyStruct
= nullptr;
1500 /// Return pointers to the start and end of a section. On ELF platforms, we
1501 /// use the __start_ and __stop_ symbols that GNU-compatible linkers will set
1502 /// to the start and end of section names, as long as those section names are
1503 /// valid identifiers and the symbols are referenced but not defined. On
1504 /// Windows, we use the fact that MSVC-compatible linkers will lexically sort
1505 /// by subsections and place everything that we want to reference in a middle
1506 /// subsection and then insert zero-sized symbols in subsections a and z.
1507 std::pair
<llvm::Constant
*,llvm::Constant
*>
1508 GetSectionBounds(StringRef Section
) {
1509 if (CGM
.getTriple().isOSBinFormatCOFF()) {
1510 if (emptyStruct
== nullptr) {
1511 emptyStruct
= llvm::StructType::create(
1512 VMContext
, {}, ".objc_section_sentinel", /*isPacked=*/true);
1514 auto ZeroInit
= llvm::Constant::getNullValue(emptyStruct
);
1515 auto Sym
= [&](StringRef Prefix
, StringRef SecSuffix
) {
1516 auto *Sym
= new llvm::GlobalVariable(TheModule
, emptyStruct
,
1517 /*isConstant*/false,
1518 llvm::GlobalValue::LinkOnceODRLinkage
, ZeroInit
, Prefix
+
1520 Sym
->setVisibility(llvm::GlobalValue::HiddenVisibility
);
1521 Sym
->setSection((Section
+ SecSuffix
).str());
1522 Sym
->setComdat(TheModule
.getOrInsertComdat((Prefix
+
1524 Sym
->setAlignment(CGM
.getPointerAlign().getAsAlign());
1527 return { Sym("__start_", "$a"), Sym("__stop", "$z") };
1529 auto *Start
= new llvm::GlobalVariable(TheModule
, PtrTy
,
1530 /*isConstant*/false,
1531 llvm::GlobalValue::ExternalLinkage
, nullptr, StringRef("__start_") +
1533 Start
->setVisibility(llvm::GlobalValue::HiddenVisibility
);
1534 auto *Stop
= new llvm::GlobalVariable(TheModule
, PtrTy
,
1535 /*isConstant*/false,
1536 llvm::GlobalValue::ExternalLinkage
, nullptr, StringRef("__stop_") +
1538 Stop
->setVisibility(llvm::GlobalValue::HiddenVisibility
);
1539 return { Start
, Stop
};
1541 CatchTypeInfo
getCatchAllTypeInfo() override
{
1542 return CGM
.getCXXABI().getCatchAllTypeInfo();
1544 llvm::Function
*ModuleInitFunction() override
{
1545 llvm::Function
*LoadFunction
= llvm::Function::Create(
1546 llvm::FunctionType::get(llvm::Type::getVoidTy(VMContext
), false),
1547 llvm::GlobalValue::LinkOnceODRLinkage
, ".objcv2_load_function",
1549 LoadFunction
->setVisibility(llvm::GlobalValue::HiddenVisibility
);
1550 LoadFunction
->setComdat(TheModule
.getOrInsertComdat(".objcv2_load_function"));
1552 llvm::BasicBlock
*EntryBB
=
1553 llvm::BasicBlock::Create(VMContext
, "entry", LoadFunction
);
1554 CGBuilderTy
B(CGM
, VMContext
);
1555 B
.SetInsertPoint(EntryBB
);
1556 ConstantInitBuilder
builder(CGM
);
1557 auto InitStructBuilder
= builder
.beginStruct();
1558 InitStructBuilder
.addInt(Int64Ty
, 0);
1559 auto §ionVec
= CGM
.getTriple().isOSBinFormatCOFF() ? PECOFFSectionsBaseNames
: SectionsBaseNames
;
1560 for (auto *s
: sectionVec
) {
1561 auto bounds
= GetSectionBounds(s
);
1562 InitStructBuilder
.add(bounds
.first
);
1563 InitStructBuilder
.add(bounds
.second
);
1565 auto *InitStruct
= InitStructBuilder
.finishAndCreateGlobal(".objc_init",
1566 CGM
.getPointerAlign(), false, llvm::GlobalValue::LinkOnceODRLinkage
);
1567 InitStruct
->setVisibility(llvm::GlobalValue::HiddenVisibility
);
1568 InitStruct
->setComdat(TheModule
.getOrInsertComdat(".objc_init"));
1570 CallRuntimeFunction(B
, "__objc_load", {InitStruct
});;
1572 // Make sure that the optimisers don't delete this function.
1573 CGM
.addCompilerUsedGlobal(LoadFunction
);
1574 // FIXME: Currently ELF only!
1575 // We have to do this by hand, rather than with @llvm.ctors, so that the
1576 // linker can remove the duplicate invocations.
1577 auto *InitVar
= new llvm::GlobalVariable(TheModule
, LoadFunction
->getType(),
1578 /*isConstant*/false, llvm::GlobalValue::LinkOnceAnyLinkage
,
1579 LoadFunction
, ".objc_ctor");
1580 // Check that this hasn't been renamed. This shouldn't happen, because
1581 // this function should be called precisely once.
1582 assert(InitVar
->getName() == ".objc_ctor");
1583 // In Windows, initialisers are sorted by the suffix. XCL is for library
1584 // initialisers, which run before user initialisers. We are running
1585 // Objective-C loads at the end of library load. This means +load methods
1586 // will run before any other static constructors, but that static
1587 // constructors can see a fully initialised Objective-C state.
1588 if (CGM
.getTriple().isOSBinFormatCOFF())
1589 InitVar
->setSection(".CRT$XCLz");
1592 if (CGM
.getCodeGenOpts().UseInitArray
)
1593 InitVar
->setSection(".init_array");
1595 InitVar
->setSection(".ctors");
1597 InitVar
->setVisibility(llvm::GlobalValue::HiddenVisibility
);
1598 InitVar
->setComdat(TheModule
.getOrInsertComdat(".objc_ctor"));
1599 CGM
.addUsedGlobal(InitVar
);
1600 for (auto *C
: Categories
) {
1601 auto *Cat
= cast
<llvm::GlobalVariable
>(C
->stripPointerCasts());
1602 Cat
->setSection(sectionName
<CategorySection
>());
1603 CGM
.addUsedGlobal(Cat
);
1605 auto createNullGlobal
= [&](StringRef Name
, ArrayRef
<llvm::Constant
*> Init
,
1606 StringRef Section
) {
1607 auto nullBuilder
= builder
.beginStruct();
1608 for (auto *F
: Init
)
1610 auto GV
= nullBuilder
.finishAndCreateGlobal(Name
, CGM
.getPointerAlign(),
1611 false, llvm::GlobalValue::LinkOnceODRLinkage
);
1612 GV
->setSection(Section
);
1613 GV
->setComdat(TheModule
.getOrInsertComdat(Name
));
1614 GV
->setVisibility(llvm::GlobalValue::HiddenVisibility
);
1615 CGM
.addUsedGlobal(GV
);
1618 for (auto clsAlias
: ClassAliases
)
1619 createNullGlobal(std::string(".objc_class_alias") +
1620 clsAlias
.second
, { MakeConstantString(clsAlias
.second
),
1621 GetClassVar(clsAlias
.first
) }, sectionName
<ClassAliasSection
>());
1622 // On ELF platforms, add a null value for each special section so that we
1623 // can always guarantee that the _start and _stop symbols will exist and be
1624 // meaningful. This is not required on COFF platforms, where our start and
1625 // stop symbols will create the section.
1626 if (!CGM
.getTriple().isOSBinFormatCOFF()) {
1627 createNullGlobal(".objc_null_selector", {NULLPtr
, NULLPtr
},
1628 sectionName
<SelectorSection
>());
1629 if (Categories
.empty())
1630 createNullGlobal(".objc_null_category", {NULLPtr
, NULLPtr
,
1631 NULLPtr
, NULLPtr
, NULLPtr
, NULLPtr
, NULLPtr
},
1632 sectionName
<CategorySection
>());
1633 if (!EmittedClass
) {
1634 createNullGlobal(".objc_null_cls_init_ref", NULLPtr
,
1635 sectionName
<ClassSection
>());
1636 createNullGlobal(".objc_null_class_ref", { NULLPtr
, NULLPtr
},
1637 sectionName
<ClassReferenceSection
>());
1639 if (!EmittedProtocol
)
1640 createNullGlobal(".objc_null_protocol", {NULLPtr
, NULLPtr
, NULLPtr
,
1641 NULLPtr
, NULLPtr
, NULLPtr
, NULLPtr
, NULLPtr
, NULLPtr
, NULLPtr
,
1642 NULLPtr
}, sectionName
<ProtocolSection
>());
1643 if (!EmittedProtocolRef
)
1644 createNullGlobal(".objc_null_protocol_ref", {NULLPtr
},
1645 sectionName
<ProtocolReferenceSection
>());
1646 if (ClassAliases
.empty())
1647 createNullGlobal(".objc_null_class_alias", { NULLPtr
, NULLPtr
},
1648 sectionName
<ClassAliasSection
>());
1649 if (ConstantStrings
.empty()) {
1650 auto i32Zero
= llvm::ConstantInt::get(Int32Ty
, 0);
1651 createNullGlobal(".objc_null_constant_string", { NULLPtr
, i32Zero
,
1652 i32Zero
, i32Zero
, i32Zero
, NULLPtr
},
1653 sectionName
<ConstantStringSection
>());
1656 ConstantStrings
.clear();
1660 if (EarlyInitList
.size() > 0) {
1661 auto *Init
= llvm::Function::Create(llvm::FunctionType::get(CGM
.VoidTy
,
1662 {}), llvm::GlobalValue::InternalLinkage
, ".objc_early_init",
1664 llvm::IRBuilder
<> b(llvm::BasicBlock::Create(CGM
.getLLVMContext(), "entry",
1666 for (const auto &lateInit
: EarlyInitList
) {
1667 auto *global
= TheModule
.getGlobalVariable(lateInit
.first
);
1669 llvm::GlobalVariable
*GV
= lateInit
.second
.first
;
1670 b
.CreateAlignedStore(
1672 b
.CreateStructGEP(GV
->getValueType(), GV
, lateInit
.second
.second
),
1673 CGM
.getPointerAlign().getAsAlign());
1677 // We can't use the normal LLVM global initialisation array, because we
1678 // need to specify that this runs early in library initialisation.
1679 auto *InitVar
= new llvm::GlobalVariable(CGM
.getModule(), Init
->getType(),
1680 /*isConstant*/true, llvm::GlobalValue::InternalLinkage
,
1681 Init
, ".objc_early_init_ptr");
1682 InitVar
->setSection(".CRT$XCLb");
1683 CGM
.addUsedGlobal(InitVar
);
1687 /// In the v2 ABI, ivar offset variables use the type encoding in their name
1688 /// to trigger linker failures if the types don't match.
1689 std::string
GetIVarOffsetVariableName(const ObjCInterfaceDecl
*ID
,
1690 const ObjCIvarDecl
*Ivar
) override
{
1691 std::string TypeEncoding
;
1692 CGM
.getContext().getObjCEncodingForType(Ivar
->getType(), TypeEncoding
);
1693 TypeEncoding
= GetSymbolNameForTypeEncoding(TypeEncoding
);
1694 const std::string Name
= "__objc_ivar_offset_" + ID
->getNameAsString()
1695 + '.' + Ivar
->getNameAsString() + '.' + TypeEncoding
;
1698 llvm::Value
*EmitIvarOffset(CodeGenFunction
&CGF
,
1699 const ObjCInterfaceDecl
*Interface
,
1700 const ObjCIvarDecl
*Ivar
) override
{
1701 const ObjCInterfaceDecl
*ContainingInterface
=
1702 Ivar
->getContainingInterface();
1703 const std::string Name
=
1704 GetIVarOffsetVariableName(ContainingInterface
, Ivar
);
1705 llvm::GlobalVariable
*IvarOffsetPointer
= TheModule
.getNamedGlobal(Name
);
1706 if (!IvarOffsetPointer
) {
1707 IvarOffsetPointer
= new llvm::GlobalVariable(TheModule
, IntTy
, false,
1708 llvm::GlobalValue::ExternalLinkage
, nullptr, Name
);
1709 if (Ivar
->getAccessControl() != ObjCIvarDecl::Private
&&
1710 Ivar
->getAccessControl() != ObjCIvarDecl::Package
)
1711 CGM
.setGVProperties(IvarOffsetPointer
, ContainingInterface
);
1713 CharUnits Align
= CGM
.getIntAlign();
1714 llvm::Value
*Offset
=
1715 CGF
.Builder
.CreateAlignedLoad(IntTy
, IvarOffsetPointer
, Align
);
1716 if (Offset
->getType() != PtrDiffTy
)
1717 Offset
= CGF
.Builder
.CreateZExtOrBitCast(Offset
, PtrDiffTy
);
1720 void GenerateClass(const ObjCImplementationDecl
*OID
) override
{
1721 ASTContext
&Context
= CGM
.getContext();
1722 bool IsCOFF
= CGM
.getTriple().isOSBinFormatCOFF();
1724 // Get the class name
1725 ObjCInterfaceDecl
*classDecl
=
1726 const_cast<ObjCInterfaceDecl
*>(OID
->getClassInterface());
1727 std::string className
= classDecl
->getNameAsString();
1728 auto *classNameConstant
= MakeConstantString(className
);
1730 ConstantInitBuilder
builder(CGM
);
1731 auto metaclassFields
= builder
.beginStruct();
1732 // struct objc_class *isa;
1733 metaclassFields
.addNullPointer(PtrTy
);
1734 // struct objc_class *super_class;
1735 metaclassFields
.addNullPointer(PtrTy
);
1736 // const char *name;
1737 metaclassFields
.add(classNameConstant
);
1739 metaclassFields
.addInt(LongTy
, 0);
1740 // unsigned long info;
1741 // objc_class_flag_meta
1742 metaclassFields
.addInt(LongTy
, ClassFlags::ClassFlagMeta
);
1743 // long instance_size;
1744 // Setting this to zero is consistent with the older ABI, but it might be
1745 // more sensible to set this to sizeof(struct objc_class)
1746 metaclassFields
.addInt(LongTy
, 0);
1747 // struct objc_ivar_list *ivars;
1748 metaclassFields
.addNullPointer(PtrTy
);
1749 // struct objc_method_list *methods
1750 // FIXME: Almost identical code is copied and pasted below for the
1751 // class, but refactoring it cleanly requires C++14 generic lambdas.
1752 if (OID
->classmeth_begin() == OID
->classmeth_end())
1753 metaclassFields
.addNullPointer(PtrTy
);
1755 SmallVector
<ObjCMethodDecl
*, 16> ClassMethods
;
1756 ClassMethods
.insert(ClassMethods
.begin(), OID
->classmeth_begin(),
1757 OID
->classmeth_end());
1758 metaclassFields
.add(
1759 GenerateMethodList(className
, "", ClassMethods
, true));
1762 metaclassFields
.addNullPointer(PtrTy
);
1763 // IMP cxx_construct;
1764 metaclassFields
.addNullPointer(PtrTy
);
1765 // IMP cxx_destruct;
1766 metaclassFields
.addNullPointer(PtrTy
);
1767 // struct objc_class *subclass_list
1768 metaclassFields
.addNullPointer(PtrTy
);
1769 // struct objc_class *sibling_class
1770 metaclassFields
.addNullPointer(PtrTy
);
1771 // struct objc_protocol_list *protocols;
1772 metaclassFields
.addNullPointer(PtrTy
);
1773 // struct reference_list *extra_data;
1774 metaclassFields
.addNullPointer(PtrTy
);
1775 // long abi_version;
1776 metaclassFields
.addInt(LongTy
, 0);
1777 // struct objc_property_list *properties
1778 metaclassFields
.add(GeneratePropertyList(OID
, classDecl
, /*isClassProperty*/true));
1780 auto *metaclass
= metaclassFields
.finishAndCreateGlobal(
1781 ManglePublicSymbol("OBJC_METACLASS_") + className
,
1782 CGM
.getPointerAlign());
1784 auto classFields
= builder
.beginStruct();
1785 // struct objc_class *isa;
1786 classFields
.add(metaclass
);
1787 // struct objc_class *super_class;
1788 // Get the superclass name.
1789 const ObjCInterfaceDecl
* SuperClassDecl
=
1790 OID
->getClassInterface()->getSuperClass();
1791 llvm::Constant
*SuperClass
= nullptr;
1792 if (SuperClassDecl
) {
1793 auto SuperClassName
= SymbolForClass(SuperClassDecl
->getNameAsString());
1794 SuperClass
= TheModule
.getNamedGlobal(SuperClassName
);
1797 SuperClass
= new llvm::GlobalVariable(TheModule
, PtrTy
, false,
1798 llvm::GlobalValue::ExternalLinkage
, nullptr, SuperClassName
);
1800 auto Storage
= llvm::GlobalValue::DefaultStorageClass
;
1801 if (SuperClassDecl
->hasAttr
<DLLImportAttr
>())
1802 Storage
= llvm::GlobalValue::DLLImportStorageClass
;
1803 else if (SuperClassDecl
->hasAttr
<DLLExportAttr
>())
1804 Storage
= llvm::GlobalValue::DLLExportStorageClass
;
1806 cast
<llvm::GlobalValue
>(SuperClass
)->setDLLStorageClass(Storage
);
1810 classFields
.add(SuperClass
);
1812 classFields
.addNullPointer(PtrTy
);
1814 classFields
.addNullPointer(PtrTy
);
1815 // const char *name;
1816 classFields
.add(classNameConstant
);
1818 classFields
.addInt(LongTy
, 0);
1819 // unsigned long info;
1820 // !objc_class_flag_meta
1821 classFields
.addInt(LongTy
, 0);
1822 // long instance_size;
1823 int superInstanceSize
= !SuperClassDecl
? 0 :
1824 Context
.getASTObjCInterfaceLayout(SuperClassDecl
).getSize().getQuantity();
1825 // Instance size is negative for classes that have not yet had their ivar
1826 // layout calculated.
1827 classFields
.addInt(LongTy
,
1828 0 - (Context
.getASTObjCImplementationLayout(OID
).getSize().getQuantity() -
1829 superInstanceSize
));
1831 if (classDecl
->all_declared_ivar_begin() == nullptr)
1832 classFields
.addNullPointer(PtrTy
);
1835 for (const ObjCIvarDecl
*IVD
= classDecl
->all_declared_ivar_begin(); IVD
;
1836 IVD
= IVD
->getNextIvar()) ivar_count
++;
1837 const llvm::DataLayout
&DL
= TheModule
.getDataLayout();
1838 // struct objc_ivar_list *ivars;
1839 ConstantInitBuilder
b(CGM
);
1840 auto ivarListBuilder
= b
.beginStruct();
1842 ivarListBuilder
.addInt(IntTy
, ivar_count
);
1844 llvm::StructType
*ObjCIvarTy
= llvm::StructType::get(
1850 ivarListBuilder
.addInt(SizeTy
, DL
.getTypeSizeInBits(ObjCIvarTy
) /
1851 CGM
.getContext().getCharWidth());
1852 // struct objc_ivar ivars[]
1853 auto ivarArrayBuilder
= ivarListBuilder
.beginArray();
1854 for (const ObjCIvarDecl
*IVD
= classDecl
->all_declared_ivar_begin(); IVD
;
1855 IVD
= IVD
->getNextIvar()) {
1856 auto ivarTy
= IVD
->getType();
1857 auto ivarBuilder
= ivarArrayBuilder
.beginStruct();
1858 // const char *name;
1859 ivarBuilder
.add(MakeConstantString(IVD
->getNameAsString()));
1860 // const char *type;
1861 std::string TypeStr
;
1862 //Context.getObjCEncodingForType(ivarTy, TypeStr, IVD, true);
1863 Context
.getObjCEncodingForMethodParameter(Decl::OBJC_TQ_None
, ivarTy
, TypeStr
, true);
1864 ivarBuilder
.add(MakeConstantString(TypeStr
));
1866 uint64_t BaseOffset
= ComputeIvarBaseOffset(CGM
, OID
, IVD
);
1867 uint64_t Offset
= BaseOffset
- superInstanceSize
;
1868 llvm::Constant
*OffsetValue
= llvm::ConstantInt::get(IntTy
, Offset
);
1869 std::string OffsetName
= GetIVarOffsetVariableName(classDecl
, IVD
);
1870 llvm::GlobalVariable
*OffsetVar
= TheModule
.getGlobalVariable(OffsetName
);
1872 OffsetVar
->setInitializer(OffsetValue
);
1874 OffsetVar
= new llvm::GlobalVariable(TheModule
, IntTy
,
1875 false, llvm::GlobalValue::ExternalLinkage
,
1876 OffsetValue
, OffsetName
);
1877 auto ivarVisibility
=
1878 (IVD
->getAccessControl() == ObjCIvarDecl::Private
||
1879 IVD
->getAccessControl() == ObjCIvarDecl::Package
||
1880 classDecl
->getVisibility() == HiddenVisibility
) ?
1881 llvm::GlobalValue::HiddenVisibility
:
1882 llvm::GlobalValue::DefaultVisibility
;
1883 OffsetVar
->setVisibility(ivarVisibility
);
1884 if (ivarVisibility
!= llvm::GlobalValue::HiddenVisibility
)
1885 CGM
.setGVProperties(OffsetVar
, OID
->getClassInterface());
1886 ivarBuilder
.add(OffsetVar
);
1888 ivarBuilder
.addInt(Int32Ty
,
1889 CGM
.getContext().getTypeSizeInChars(ivarTy
).getQuantity());
1890 // Alignment will be stored as a base-2 log of the alignment.
1892 llvm::Log2_32(Context
.getTypeAlignInChars(ivarTy
).getQuantity());
1893 // Objects that require more than 2^64-byte alignment should be impossible!
1896 // Bits 0-1 are ownership.
1897 // Bit 2 indicates an extended type encoding
1898 // Bits 3-8 contain log2(aligment)
1899 ivarBuilder
.addInt(Int32Ty
,
1900 (align
<< 3) | (1<<2) |
1901 FlagsForOwnership(ivarTy
.getQualifiers().getObjCLifetime()));
1902 ivarBuilder
.finishAndAddTo(ivarArrayBuilder
);
1904 ivarArrayBuilder
.finishAndAddTo(ivarListBuilder
);
1905 auto ivarList
= ivarListBuilder
.finishAndCreateGlobal(".objc_ivar_list",
1906 CGM
.getPointerAlign(), /*constant*/ false,
1907 llvm::GlobalValue::PrivateLinkage
);
1908 classFields
.add(ivarList
);
1910 // struct objc_method_list *methods
1911 SmallVector
<const ObjCMethodDecl
*, 16> InstanceMethods
;
1912 InstanceMethods
.insert(InstanceMethods
.begin(), OID
->instmeth_begin(),
1913 OID
->instmeth_end());
1914 for (auto *propImpl
: OID
->property_impls())
1915 if (propImpl
->getPropertyImplementation() ==
1916 ObjCPropertyImplDecl::Synthesize
) {
1917 auto addIfExists
= [&](const ObjCMethodDecl
*OMD
) {
1918 if (OMD
&& OMD
->hasBody())
1919 InstanceMethods
.push_back(OMD
);
1921 addIfExists(propImpl
->getGetterMethodDecl());
1922 addIfExists(propImpl
->getSetterMethodDecl());
1925 if (InstanceMethods
.size() == 0)
1926 classFields
.addNullPointer(PtrTy
);
1929 GenerateMethodList(className
, "", InstanceMethods
, false));
1932 classFields
.addNullPointer(PtrTy
);
1933 // IMP cxx_construct;
1934 classFields
.addNullPointer(PtrTy
);
1935 // IMP cxx_destruct;
1936 classFields
.addNullPointer(PtrTy
);
1937 // struct objc_class *subclass_list
1938 classFields
.addNullPointer(PtrTy
);
1939 // struct objc_class *sibling_class
1940 classFields
.addNullPointer(PtrTy
);
1941 // struct objc_protocol_list *protocols;
1942 auto RuntimeProtocols
= GetRuntimeProtocolList(classDecl
->protocol_begin(),
1943 classDecl
->protocol_end());
1944 SmallVector
<llvm::Constant
*, 16> Protocols
;
1945 for (const auto *I
: RuntimeProtocols
)
1946 Protocols
.push_back(GenerateProtocolRef(I
));
1948 if (Protocols
.empty())
1949 classFields
.addNullPointer(PtrTy
);
1951 classFields
.add(GenerateProtocolList(Protocols
));
1952 // struct reference_list *extra_data;
1953 classFields
.addNullPointer(PtrTy
);
1954 // long abi_version;
1955 classFields
.addInt(LongTy
, 0);
1956 // struct objc_property_list *properties
1957 classFields
.add(GeneratePropertyList(OID
, classDecl
));
1959 llvm::GlobalVariable
*classStruct
=
1960 classFields
.finishAndCreateGlobal(SymbolForClass(className
),
1961 CGM
.getPointerAlign(), false, llvm::GlobalValue::ExternalLinkage
);
1963 auto *classRefSymbol
= GetClassVar(className
);
1964 classRefSymbol
->setSection(sectionName
<ClassReferenceSection
>());
1965 classRefSymbol
->setInitializer(classStruct
);
1968 // we can't import a class struct.
1969 if (OID
->getClassInterface()->hasAttr
<DLLExportAttr
>()) {
1970 classStruct
->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass
);
1971 cast
<llvm::GlobalValue
>(classRefSymbol
)->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass
);
1975 std::pair
<llvm::GlobalVariable
*, int> v
{classStruct
, 1};
1976 EarlyInitList
.emplace_back(std::string(SuperClass
->getName()),
1983 // Resolve the class aliases, if they exist.
1984 // FIXME: Class pointer aliases shouldn't exist!
1985 if (ClassPtrAlias
) {
1986 ClassPtrAlias
->replaceAllUsesWith(classStruct
);
1987 ClassPtrAlias
->eraseFromParent();
1988 ClassPtrAlias
= nullptr;
1990 if (auto Placeholder
=
1991 TheModule
.getNamedGlobal(SymbolForClass(className
)))
1992 if (Placeholder
!= classStruct
) {
1993 Placeholder
->replaceAllUsesWith(classStruct
);
1994 Placeholder
->eraseFromParent();
1995 classStruct
->setName(SymbolForClass(className
));
1997 if (MetaClassPtrAlias
) {
1998 MetaClassPtrAlias
->replaceAllUsesWith(metaclass
);
1999 MetaClassPtrAlias
->eraseFromParent();
2000 MetaClassPtrAlias
= nullptr;
2002 assert(classStruct
->getName() == SymbolForClass(className
));
2004 auto classInitRef
= new llvm::GlobalVariable(TheModule
,
2005 classStruct
->getType(), false, llvm::GlobalValue::ExternalLinkage
,
2006 classStruct
, ManglePublicSymbol("OBJC_INIT_CLASS_") + className
);
2007 classInitRef
->setSection(sectionName
<ClassSection
>());
2008 CGM
.addUsedGlobal(classInitRef
);
2010 EmittedClass
= true;
2013 CGObjCGNUstep2(CodeGenModule
&Mod
) : CGObjCGNUstep(Mod
, 10, 4, 2) {
2014 MsgLookupSuperFn
.init(&CGM
, "objc_msg_lookup_super", IMPTy
,
2015 PtrToObjCSuperTy
, SelectorTy
);
2016 SentInitializeFn
.init(&CGM
, "objc_send_initialize",
2017 llvm::Type::getVoidTy(VMContext
), IdTy
);
2018 // struct objc_property
2020 // const char *name;
2021 // const char *attributes;
2022 // const char *type;
2026 PropertyMetadataTy
=
2027 llvm::StructType::get(CGM
.getLLVMContext(),
2028 { PtrToInt8Ty
, PtrToInt8Ty
, PtrToInt8Ty
, PtrToInt8Ty
, PtrToInt8Ty
});
2031 void GenerateDirectMethodPrologue(CodeGenFunction
&CGF
, llvm::Function
*Fn
,
2032 const ObjCMethodDecl
*OMD
,
2033 const ObjCContainerDecl
*CD
) override
{
2034 auto &Builder
= CGF
.Builder
;
2035 bool ReceiverCanBeNull
= true;
2036 auto selfAddr
= CGF
.GetAddrOfLocalVar(OMD
->getSelfDecl());
2037 auto selfValue
= Builder
.CreateLoad(selfAddr
);
2041 // /* unless the receiver is never NULL */
2042 // if (self == nil) {
2043 // return (ReturnType){ };
2046 // /* for class methods only to force class lazy initialization */
2047 // if (!__objc_{class}_initialized)
2049 // objc_send_initialize(class);
2050 // __objc_{class}_initialized = 1;
2053 // _cmd = @selector(...)
2056 if (OMD
->isClassMethod()) {
2057 const ObjCInterfaceDecl
*OID
= cast
<ObjCInterfaceDecl
>(CD
);
2059 // Nullable `Class` expressions cannot be messaged with a direct method
2060 // so the only reason why the receive can be null would be because
2062 ReceiverCanBeNull
= isWeakLinkedClass(OID
);
2065 llvm::MDBuilder
MDHelper(CGM
.getLLVMContext());
2066 if (ReceiverCanBeNull
) {
2067 llvm::BasicBlock
*SelfIsNilBlock
=
2068 CGF
.createBasicBlock("objc_direct_method.self_is_nil");
2069 llvm::BasicBlock
*ContBlock
=
2070 CGF
.createBasicBlock("objc_direct_method.cont");
2072 // if (self == nil) {
2073 auto selfTy
= cast
<llvm::PointerType
>(selfValue
->getType());
2074 auto Zero
= llvm::ConstantPointerNull::get(selfTy
);
2076 Builder
.CreateCondBr(Builder
.CreateICmpEQ(selfValue
, Zero
),
2077 SelfIsNilBlock
, ContBlock
,
2078 MDHelper
.createUnlikelyBranchWeights());
2080 CGF
.EmitBlock(SelfIsNilBlock
);
2082 // return (ReturnType){ };
2083 auto retTy
= OMD
->getReturnType();
2084 Builder
.SetInsertPoint(SelfIsNilBlock
);
2085 if (!retTy
->isVoidType()) {
2086 CGF
.EmitNullInitialization(CGF
.ReturnValue
, retTy
);
2088 CGF
.EmitBranchThroughCleanup(CGF
.ReturnBlock
);
2092 CGF
.EmitBlock(ContBlock
);
2093 Builder
.SetInsertPoint(ContBlock
);
2096 if (OMD
->isClassMethod()) {
2097 // Prefix of the class type.
2099 llvm::StructType::get(PtrTy
, PtrTy
, PtrTy
, LongTy
, LongTy
);
2100 auto &astContext
= CGM
.getContext();
2101 // FIXME: The following few lines up to and including the call to
2102 // `CreateLoad` were known to miscompile when MSVC 19.40.33813 is used
2103 // to build Clang. When the bug is fixed in future MSVC releases, we
2104 // should revert these lines to their previous state. See discussion in
2105 // https://github.com/llvm/llvm-project/pull/102681
2106 llvm::Value
*Val
= Builder
.CreateStructGEP(classStart
, selfValue
, 4);
2107 auto Align
= CharUnits::fromQuantity(
2108 astContext
.getTypeAlign(astContext
.UnsignedLongTy
));
2109 auto flags
= Builder
.CreateLoad(Address
{Val
, LongTy
, Align
});
2110 auto isInitialized
=
2111 Builder
.CreateAnd(flags
, ClassFlags::ClassFlagInitialized
);
2112 llvm::BasicBlock
*notInitializedBlock
=
2113 CGF
.createBasicBlock("objc_direct_method.class_uninitialized");
2114 llvm::BasicBlock
*initializedBlock
=
2115 CGF
.createBasicBlock("objc_direct_method.class_initialized");
2116 Builder
.CreateCondBr(Builder
.CreateICmpEQ(isInitialized
, Zeros
[0]),
2117 notInitializedBlock
, initializedBlock
,
2118 MDHelper
.createUnlikelyBranchWeights());
2119 CGF
.EmitBlock(notInitializedBlock
);
2120 Builder
.SetInsertPoint(notInitializedBlock
);
2121 CGF
.EmitRuntimeCall(SentInitializeFn
, selfValue
);
2122 Builder
.CreateBr(initializedBlock
);
2123 CGF
.EmitBlock(initializedBlock
);
2124 Builder
.SetInsertPoint(initializedBlock
);
2127 // only synthesize _cmd if it's referenced
2128 if (OMD
->getCmdDecl()->isUsed()) {
2129 // `_cmd` is not a parameter to direct methods, so storage must be
2130 // explicitly declared for it.
2131 CGF
.EmitVarDecl(*OMD
->getCmdDecl());
2132 Builder
.CreateStore(GetSelector(CGF
, OMD
),
2133 CGF
.GetAddrOfLocalVar(OMD
->getCmdDecl()));
2138 const char *const CGObjCGNUstep2::SectionsBaseNames
[8] =
2142 "__objc_class_refs",
2145 "__objc_protocol_refs",
2146 "__objc_class_aliases",
2147 "__objc_constant_string"
2150 const char *const CGObjCGNUstep2::PECOFFSectionsBaseNames
[8] =
2162 /// Support for the ObjFW runtime.
2163 class CGObjCObjFW
: public CGObjCGNU
{
2165 /// The GCC ABI message lookup function. Returns an IMP pointing to the
2166 /// method implementation for this message.
2167 LazyRuntimeFunction MsgLookupFn
;
2168 /// stret lookup function. While this does not seem to make sense at the
2169 /// first look, this is required to call the correct forwarding function.
2170 LazyRuntimeFunction MsgLookupFnSRet
;
2171 /// The GCC ABI superclass message lookup function. Takes a pointer to a
2172 /// structure describing the receiver and the class, and a selector as
2173 /// arguments. Returns the IMP for the corresponding method.
2174 LazyRuntimeFunction MsgLookupSuperFn
, MsgLookupSuperFnSRet
;
2176 llvm::Value
*LookupIMP(CodeGenFunction
&CGF
, llvm::Value
*&Receiver
,
2177 llvm::Value
*cmd
, llvm::MDNode
*node
,
2178 MessageSendInfo
&MSI
) override
{
2179 CGBuilderTy
&Builder
= CGF
.Builder
;
2180 llvm::Value
*args
[] = {
2181 EnforceType(Builder
, Receiver
, IdTy
),
2182 EnforceType(Builder
, cmd
, SelectorTy
) };
2184 llvm::CallBase
*imp
;
2185 if (CGM
.ReturnTypeUsesSRet(MSI
.CallInfo
))
2186 imp
= CGF
.EmitRuntimeCallOrInvoke(MsgLookupFnSRet
, args
);
2188 imp
= CGF
.EmitRuntimeCallOrInvoke(MsgLookupFn
, args
);
2190 imp
->setMetadata(msgSendMDKind
, node
);
2194 llvm::Value
*LookupIMPSuper(CodeGenFunction
&CGF
, Address ObjCSuper
,
2195 llvm::Value
*cmd
, MessageSendInfo
&MSI
) override
{
2196 CGBuilderTy
&Builder
= CGF
.Builder
;
2197 llvm::Value
*lookupArgs
[] = {
2198 EnforceType(Builder
, ObjCSuper
.emitRawPointer(CGF
), PtrToObjCSuperTy
),
2202 if (CGM
.ReturnTypeUsesSRet(MSI
.CallInfo
))
2203 return CGF
.EmitNounwindRuntimeCall(MsgLookupSuperFnSRet
, lookupArgs
);
2205 return CGF
.EmitNounwindRuntimeCall(MsgLookupSuperFn
, lookupArgs
);
2208 llvm::Value
*GetClassNamed(CodeGenFunction
&CGF
, const std::string
&Name
,
2209 bool isWeak
) override
{
2211 return CGObjCGNU::GetClassNamed(CGF
, Name
, isWeak
);
2214 std::string SymbolName
= "_OBJC_CLASS_" + Name
;
2215 llvm::GlobalVariable
*ClassSymbol
= TheModule
.getGlobalVariable(SymbolName
);
2217 ClassSymbol
= new llvm::GlobalVariable(TheModule
, LongTy
, false,
2218 llvm::GlobalValue::ExternalLinkage
,
2219 nullptr, SymbolName
);
2224 CGObjCObjFW(CodeGenModule
&Mod
): CGObjCGNU(Mod
, 9, 3) {
2225 // IMP objc_msg_lookup(id, SEL);
2226 MsgLookupFn
.init(&CGM
, "objc_msg_lookup", IMPTy
, IdTy
, SelectorTy
);
2227 MsgLookupFnSRet
.init(&CGM
, "objc_msg_lookup_stret", IMPTy
, IdTy
,
2229 // IMP objc_msg_lookup_super(struct objc_super*, SEL);
2230 MsgLookupSuperFn
.init(&CGM
, "objc_msg_lookup_super", IMPTy
,
2231 PtrToObjCSuperTy
, SelectorTy
);
2232 MsgLookupSuperFnSRet
.init(&CGM
, "objc_msg_lookup_super_stret", IMPTy
,
2233 PtrToObjCSuperTy
, SelectorTy
);
2236 } // end anonymous namespace
2238 /// Emits a reference to a dummy variable which is emitted with each class.
2239 /// This ensures that a linker error will be generated when trying to link
2240 /// together modules where a referenced class is not defined.
2241 void CGObjCGNU::EmitClassRef(const std::string
&className
) {
2242 std::string symbolRef
= "__objc_class_ref_" + className
;
2243 // Don't emit two copies of the same symbol
2244 if (TheModule
.getGlobalVariable(symbolRef
))
2246 std::string symbolName
= "__objc_class_name_" + className
;
2247 llvm::GlobalVariable
*ClassSymbol
= TheModule
.getGlobalVariable(symbolName
);
2249 ClassSymbol
= new llvm::GlobalVariable(TheModule
, LongTy
, false,
2250 llvm::GlobalValue::ExternalLinkage
,
2251 nullptr, symbolName
);
2253 new llvm::GlobalVariable(TheModule
, ClassSymbol
->getType(), true,
2254 llvm::GlobalValue::WeakAnyLinkage
, ClassSymbol
, symbolRef
);
2257 CGObjCGNU::CGObjCGNU(CodeGenModule
&cgm
, unsigned runtimeABIVersion
,
2258 unsigned protocolClassVersion
, unsigned classABI
)
2259 : CGObjCRuntime(cgm
), TheModule(CGM
.getModule()),
2260 VMContext(cgm
.getLLVMContext()), ClassPtrAlias(nullptr),
2261 MetaClassPtrAlias(nullptr), RuntimeVersion(runtimeABIVersion
),
2262 ProtocolVersion(protocolClassVersion
), ClassABIVersion(classABI
) {
2264 msgSendMDKind
= VMContext
.getMDKindID("GNUObjCMessageSend");
2266 cgm
.getContext().getTargetInfo().getTriple().isWindowsMSVCEnvironment();
2268 cgm
.getContext().getTargetInfo().getTriple().isOSCygMing() &&
2269 isRuntime(ObjCRuntime::GNUstep
, 2);
2271 CodeGenTypes
&Types
= CGM
.getTypes();
2272 IntTy
= cast
<llvm::IntegerType
>(
2273 Types
.ConvertType(CGM
.getContext().IntTy
));
2274 LongTy
= cast
<llvm::IntegerType
>(
2275 Types
.ConvertType(CGM
.getContext().LongTy
));
2276 SizeTy
= cast
<llvm::IntegerType
>(
2277 Types
.ConvertType(CGM
.getContext().getSizeType()));
2278 PtrDiffTy
= cast
<llvm::IntegerType
>(
2279 Types
.ConvertType(CGM
.getContext().getPointerDiffType()));
2280 BoolTy
= CGM
.getTypes().ConvertType(CGM
.getContext().BoolTy
);
2282 Int8Ty
= llvm::Type::getInt8Ty(VMContext
);
2283 // C string type. Used in lots of places.
2284 PtrToInt8Ty
= llvm::PointerType::getUnqual(Int8Ty
);
2285 ProtocolPtrTy
= llvm::PointerType::getUnqual(
2286 Types
.ConvertType(CGM
.getContext().getObjCProtoType()));
2288 Zeros
[0] = llvm::ConstantInt::get(LongTy
, 0);
2289 Zeros
[1] = Zeros
[0];
2290 NULLPtr
= llvm::ConstantPointerNull::get(PtrToInt8Ty
);
2291 // Get the selector Type.
2292 QualType selTy
= CGM
.getContext().getObjCSelType();
2293 if (QualType() == selTy
) {
2294 SelectorTy
= PtrToInt8Ty
;
2295 SelectorElemTy
= Int8Ty
;
2297 SelectorTy
= cast
<llvm::PointerType
>(CGM
.getTypes().ConvertType(selTy
));
2298 SelectorElemTy
= CGM
.getTypes().ConvertTypeForMem(selTy
->getPointeeType());
2301 PtrToIntTy
= llvm::PointerType::getUnqual(IntTy
);
2302 PtrTy
= PtrToInt8Ty
;
2304 Int32Ty
= llvm::Type::getInt32Ty(VMContext
);
2305 Int64Ty
= llvm::Type::getInt64Ty(VMContext
);
2308 CGM
.getDataLayout().getPointerSizeInBits() == 32 ? Int32Ty
: Int64Ty
;
2311 QualType UnqualIdTy
= CGM
.getContext().getObjCIdType();
2312 ASTIdTy
= CanQualType();
2313 if (UnqualIdTy
!= QualType()) {
2314 ASTIdTy
= CGM
.getContext().getCanonicalType(UnqualIdTy
);
2315 IdTy
= cast
<llvm::PointerType
>(CGM
.getTypes().ConvertType(ASTIdTy
));
2316 IdElemTy
= CGM
.getTypes().ConvertTypeForMem(
2317 ASTIdTy
.getTypePtr()->getPointeeType());
2322 PtrToIdTy
= llvm::PointerType::getUnqual(IdTy
);
2323 ProtocolTy
= llvm::StructType::get(IdTy
,
2324 PtrToInt8Ty
, // name
2325 PtrToInt8Ty
, // protocols
2326 PtrToInt8Ty
, // instance methods
2327 PtrToInt8Ty
, // class methods
2328 PtrToInt8Ty
, // optional instance methods
2329 PtrToInt8Ty
, // optional class methods
2330 PtrToInt8Ty
, // properties
2331 PtrToInt8Ty
);// optional properties
2333 // struct objc_property_gsv1
2335 // const char *name;
2337 // char attributes2;
2340 // const char *getter_name;
2341 // const char *getter_types;
2342 // const char *setter_name;
2343 // const char *setter_types;
2345 PropertyMetadataTy
= llvm::StructType::get(CGM
.getLLVMContext(), {
2346 PtrToInt8Ty
, Int8Ty
, Int8Ty
, Int8Ty
, Int8Ty
, PtrToInt8Ty
, PtrToInt8Ty
,
2347 PtrToInt8Ty
, PtrToInt8Ty
});
2349 ObjCSuperTy
= llvm::StructType::get(IdTy
, IdTy
);
2350 PtrToObjCSuperTy
= llvm::PointerType::getUnqual(ObjCSuperTy
);
2352 llvm::Type
*VoidTy
= llvm::Type::getVoidTy(VMContext
);
2354 // void objc_exception_throw(id);
2355 ExceptionThrowFn
.init(&CGM
, "objc_exception_throw", VoidTy
, IdTy
);
2356 ExceptionReThrowFn
.init(&CGM
,
2357 usesCxxExceptions
? "objc_exception_rethrow"
2358 : "objc_exception_throw",
2360 // int objc_sync_enter(id);
2361 SyncEnterFn
.init(&CGM
, "objc_sync_enter", IntTy
, IdTy
);
2362 // int objc_sync_exit(id);
2363 SyncExitFn
.init(&CGM
, "objc_sync_exit", IntTy
, IdTy
);
2365 // void objc_enumerationMutation (id)
2366 EnumerationMutationFn
.init(&CGM
, "objc_enumerationMutation", VoidTy
, IdTy
);
2368 // id objc_getProperty(id, SEL, ptrdiff_t, BOOL)
2369 GetPropertyFn
.init(&CGM
, "objc_getProperty", IdTy
, IdTy
, SelectorTy
,
2371 // void objc_setProperty(id, SEL, ptrdiff_t, id, BOOL, BOOL)
2372 SetPropertyFn
.init(&CGM
, "objc_setProperty", VoidTy
, IdTy
, SelectorTy
,
2373 PtrDiffTy
, IdTy
, BoolTy
, BoolTy
);
2374 // void objc_setPropertyStruct(void*, void*, ptrdiff_t, BOOL, BOOL)
2375 GetStructPropertyFn
.init(&CGM
, "objc_getPropertyStruct", VoidTy
, PtrTy
, PtrTy
,
2376 PtrDiffTy
, BoolTy
, BoolTy
);
2377 // void objc_setPropertyStruct(void*, void*, ptrdiff_t, BOOL, BOOL)
2378 SetStructPropertyFn
.init(&CGM
, "objc_setPropertyStruct", VoidTy
, PtrTy
, PtrTy
,
2379 PtrDiffTy
, BoolTy
, BoolTy
);
2382 llvm::Type
*IMPArgs
[] = { IdTy
, SelectorTy
};
2383 IMPTy
= llvm::PointerType::getUnqual(llvm::FunctionType::get(IdTy
, IMPArgs
,
2386 const LangOptions
&Opts
= CGM
.getLangOpts();
2387 if ((Opts
.getGC() != LangOptions::NonGC
) || Opts
.ObjCAutoRefCount
)
2388 RuntimeVersion
= 10;
2390 // Don't bother initialising the GC stuff unless we're compiling in GC mode
2391 if (Opts
.getGC() != LangOptions::NonGC
) {
2392 // This is a bit of an hack. We should sort this out by having a proper
2393 // CGObjCGNUstep subclass for GC, but we may want to really support the old
2394 // ABI and GC added in ObjectiveC2.framework, so we fudge it a bit for now
2395 // Get selectors needed in GC mode
2396 RetainSel
= GetNullarySelector("retain", CGM
.getContext());
2397 ReleaseSel
= GetNullarySelector("release", CGM
.getContext());
2398 AutoreleaseSel
= GetNullarySelector("autorelease", CGM
.getContext());
2400 // Get functions needed in GC mode
2402 // id objc_assign_ivar(id, id, ptrdiff_t);
2403 IvarAssignFn
.init(&CGM
, "objc_assign_ivar", IdTy
, IdTy
, IdTy
, PtrDiffTy
);
2404 // id objc_assign_strongCast (id, id*)
2405 StrongCastAssignFn
.init(&CGM
, "objc_assign_strongCast", IdTy
, IdTy
,
2407 // id objc_assign_global(id, id*);
2408 GlobalAssignFn
.init(&CGM
, "objc_assign_global", IdTy
, IdTy
, PtrToIdTy
);
2409 // id objc_assign_weak(id, id*);
2410 WeakAssignFn
.init(&CGM
, "objc_assign_weak", IdTy
, IdTy
, PtrToIdTy
);
2411 // id objc_read_weak(id*);
2412 WeakReadFn
.init(&CGM
, "objc_read_weak", IdTy
, PtrToIdTy
);
2413 // void *objc_memmove_collectable(void*, void *, size_t);
2414 MemMoveFn
.init(&CGM
, "objc_memmove_collectable", PtrTy
, PtrTy
, PtrTy
,
2419 llvm::Value
*CGObjCGNU::GetClassNamed(CodeGenFunction
&CGF
,
2420 const std::string
&Name
, bool isWeak
) {
2421 llvm::Constant
*ClassName
= MakeConstantString(Name
);
2422 // With the incompatible ABI, this will need to be replaced with a direct
2423 // reference to the class symbol. For the compatible nonfragile ABI we are
2424 // still performing this lookup at run time but emitting the symbol for the
2425 // class externally so that we can make the switch later.
2427 // Libobjc2 contains an LLVM pass that replaces calls to objc_lookup_class
2428 // with memoized versions or with static references if it's safe to do so.
2432 llvm::FunctionCallee ClassLookupFn
= CGM
.CreateRuntimeFunction(
2433 llvm::FunctionType::get(IdTy
, PtrToInt8Ty
, true), "objc_lookup_class");
2434 return CGF
.EmitNounwindRuntimeCall(ClassLookupFn
, ClassName
);
2437 // This has to perform the lookup every time, since posing and related
2438 // techniques can modify the name -> class mapping.
2439 llvm::Value
*CGObjCGNU::GetClass(CodeGenFunction
&CGF
,
2440 const ObjCInterfaceDecl
*OID
) {
2442 GetClassNamed(CGF
, OID
->getNameAsString(), OID
->isWeakImported());
2443 if (auto *ClassSymbol
= dyn_cast
<llvm::GlobalVariable
>(Value
))
2444 CGM
.setGVProperties(ClassSymbol
, OID
);
2448 llvm::Value
*CGObjCGNU::EmitNSAutoreleasePoolClassRef(CodeGenFunction
&CGF
) {
2449 auto *Value
= GetClassNamed(CGF
, "NSAutoreleasePool", false);
2450 if (CGM
.getTriple().isOSBinFormatCOFF()) {
2451 if (auto *ClassSymbol
= dyn_cast
<llvm::GlobalVariable
>(Value
)) {
2452 IdentifierInfo
&II
= CGF
.CGM
.getContext().Idents
.get("NSAutoreleasePool");
2453 TranslationUnitDecl
*TUDecl
= CGM
.getContext().getTranslationUnitDecl();
2454 DeclContext
*DC
= TranslationUnitDecl::castToDeclContext(TUDecl
);
2456 const VarDecl
*VD
= nullptr;
2457 for (const auto *Result
: DC
->lookup(&II
))
2458 if ((VD
= dyn_cast
<VarDecl
>(Result
)))
2461 CGM
.setGVProperties(ClassSymbol
, VD
);
2467 llvm::Value
*CGObjCGNU::GetTypedSelector(CodeGenFunction
&CGF
, Selector Sel
,
2468 const std::string
&TypeEncoding
) {
2469 SmallVectorImpl
<TypedSelector
> &Types
= SelectorTable
[Sel
];
2470 llvm::GlobalAlias
*SelValue
= nullptr;
2472 for (SmallVectorImpl
<TypedSelector
>::iterator i
= Types
.begin(),
2473 e
= Types
.end() ; i
!=e
; i
++) {
2474 if (i
->first
== TypeEncoding
) {
2475 SelValue
= i
->second
;
2480 SelValue
= llvm::GlobalAlias::create(SelectorElemTy
, 0,
2481 llvm::GlobalValue::PrivateLinkage
,
2482 ".objc_selector_" + Sel
.getAsString(),
2484 Types
.emplace_back(TypeEncoding
, SelValue
);
2490 Address
CGObjCGNU::GetAddrOfSelector(CodeGenFunction
&CGF
, Selector Sel
) {
2491 llvm::Value
*SelValue
= GetSelector(CGF
, Sel
);
2493 // Store it to a temporary. Does this satisfy the semantics of
2494 // GetAddrOfSelector? Hopefully.
2495 Address tmp
= CGF
.CreateTempAlloca(SelValue
->getType(),
2496 CGF
.getPointerAlign());
2497 CGF
.Builder
.CreateStore(SelValue
, tmp
);
2501 llvm::Value
*CGObjCGNU::GetSelector(CodeGenFunction
&CGF
, Selector Sel
) {
2502 return GetTypedSelector(CGF
, Sel
, std::string());
2505 llvm::Value
*CGObjCGNU::GetSelector(CodeGenFunction
&CGF
,
2506 const ObjCMethodDecl
*Method
) {
2507 std::string SelTypes
= CGM
.getContext().getObjCEncodingForMethodDecl(Method
);
2508 return GetTypedSelector(CGF
, Method
->getSelector(), SelTypes
);
2511 llvm::Constant
*CGObjCGNU::GetEHType(QualType T
) {
2512 if (T
->isObjCIdType() || T
->isObjCQualifiedIdType()) {
2513 // With the old ABI, there was only one kind of catchall, which broke
2514 // foreign exceptions. With the new ABI, we use __objc_id_typeinfo as
2515 // a pointer indicating object catchalls, and NULL to indicate real
2517 if (CGM
.getLangOpts().ObjCRuntime
.isNonFragile()) {
2518 return MakeConstantString("@id");
2524 // All other types should be Objective-C interface pointer types.
2525 const ObjCObjectPointerType
*OPT
= T
->getAs
<ObjCObjectPointerType
>();
2526 assert(OPT
&& "Invalid @catch type.");
2527 const ObjCInterfaceDecl
*IDecl
= OPT
->getObjectType()->getInterface();
2528 assert(IDecl
&& "Invalid @catch type.");
2529 return MakeConstantString(IDecl
->getIdentifier()->getName());
2532 llvm::Constant
*CGObjCGNUstep::GetEHType(QualType T
) {
2533 if (usesSEHExceptions
)
2534 return CGM
.getCXXABI().getAddrOfRTTIDescriptor(T
);
2536 if (!CGM
.getLangOpts().CPlusPlus
&& !usesCxxExceptions
)
2537 return CGObjCGNU::GetEHType(T
);
2539 // For Objective-C++, we want to provide the ability to catch both C++ and
2540 // Objective-C objects in the same function.
2542 // There's a particular fixed type info for 'id'.
2543 if (T
->isObjCIdType() ||
2544 T
->isObjCQualifiedIdType()) {
2545 llvm::Constant
*IDEHType
=
2546 CGM
.getModule().getGlobalVariable("__objc_id_type_info");
2549 new llvm::GlobalVariable(CGM
.getModule(), PtrToInt8Ty
,
2551 llvm::GlobalValue::ExternalLinkage
,
2552 nullptr, "__objc_id_type_info");
2556 const ObjCObjectPointerType
*PT
=
2557 T
->getAs
<ObjCObjectPointerType
>();
2558 assert(PT
&& "Invalid @catch type.");
2559 const ObjCInterfaceType
*IT
= PT
->getInterfaceType();
2560 assert(IT
&& "Invalid @catch type.");
2561 std::string className
=
2562 std::string(IT
->getDecl()->getIdentifier()->getName());
2564 std::string typeinfoName
= "__objc_eh_typeinfo_" + className
;
2566 // Return the existing typeinfo if it exists
2567 if (llvm::Constant
*typeinfo
= TheModule
.getGlobalVariable(typeinfoName
))
2570 // Otherwise create it.
2572 // vtable for gnustep::libobjc::__objc_class_type_info
2573 // It's quite ugly hard-coding this. Ideally we'd generate it using the host
2574 // platform's name mangling.
2575 const char *vtableName
= "_ZTVN7gnustep7libobjc22__objc_class_type_infoE";
2576 auto *Vtable
= TheModule
.getGlobalVariable(vtableName
);
2578 Vtable
= new llvm::GlobalVariable(TheModule
, PtrToInt8Ty
, true,
2579 llvm::GlobalValue::ExternalLinkage
,
2580 nullptr, vtableName
);
2582 llvm::Constant
*Two
= llvm::ConstantInt::get(IntTy
, 2);
2584 llvm::ConstantExpr::getGetElementPtr(Vtable
->getValueType(), Vtable
, Two
);
2586 llvm::Constant
*typeName
=
2587 ExportUniqueString(className
, "__objc_eh_typename_");
2589 ConstantInitBuilder
builder(CGM
);
2590 auto fields
= builder
.beginStruct();
2591 fields
.add(BVtable
);
2592 fields
.add(typeName
);
2593 llvm::Constant
*TI
=
2594 fields
.finishAndCreateGlobal("__objc_eh_typeinfo_" + className
,
2595 CGM
.getPointerAlign(),
2597 llvm::GlobalValue::LinkOnceODRLinkage
);
2601 /// Generate an NSConstantString object.
2602 ConstantAddress
CGObjCGNU::GenerateConstantString(const StringLiteral
*SL
) {
2604 std::string Str
= SL
->getString().str();
2605 CharUnits Align
= CGM
.getPointerAlign();
2607 // Look for an existing one
2608 llvm::StringMap
<llvm::Constant
*>::iterator old
= ObjCStrings
.find(Str
);
2609 if (old
!= ObjCStrings
.end())
2610 return ConstantAddress(old
->getValue(), Int8Ty
, Align
);
2612 StringRef StringClass
= CGM
.getLangOpts().ObjCConstantStringClass
;
2614 if (StringClass
.empty()) StringClass
= "NSConstantString";
2616 std::string Sym
= "_OBJC_CLASS_";
2619 llvm::Constant
*isa
= TheModule
.getNamedGlobal(Sym
);
2622 isa
= new llvm::GlobalVariable(TheModule
, IdTy
, /* isConstant */ false,
2623 llvm::GlobalValue::ExternalWeakLinkage
,
2626 ConstantInitBuilder
Builder(CGM
);
2627 auto Fields
= Builder
.beginStruct();
2629 Fields
.add(MakeConstantString(Str
));
2630 Fields
.addInt(IntTy
, Str
.size());
2631 llvm::Constant
*ObjCStr
= Fields
.finishAndCreateGlobal(".objc_str", Align
);
2632 ObjCStrings
[Str
] = ObjCStr
;
2633 ConstantStrings
.push_back(ObjCStr
);
2634 return ConstantAddress(ObjCStr
, Int8Ty
, Align
);
2637 ///Generates a message send where the super is the receiver. This is a message
2638 ///send to self with special delivery semantics indicating which class's method
2639 ///should be called.
2641 CGObjCGNU::GenerateMessageSendSuper(CodeGenFunction
&CGF
,
2642 ReturnValueSlot Return
,
2643 QualType ResultType
,
2645 const ObjCInterfaceDecl
*Class
,
2646 bool isCategoryImpl
,
2647 llvm::Value
*Receiver
,
2648 bool IsClassMessage
,
2649 const CallArgList
&CallArgs
,
2650 const ObjCMethodDecl
*Method
) {
2651 CGBuilderTy
&Builder
= CGF
.Builder
;
2652 if (CGM
.getLangOpts().getGC() == LangOptions::GCOnly
) {
2653 if (Sel
== RetainSel
|| Sel
== AutoreleaseSel
) {
2654 return RValue::get(EnforceType(Builder
, Receiver
,
2655 CGM
.getTypes().ConvertType(ResultType
)));
2657 if (Sel
== ReleaseSel
) {
2658 return RValue::get(nullptr);
2662 llvm::Value
*cmd
= GetSelector(CGF
, Sel
);
2663 CallArgList ActualArgs
;
2665 ActualArgs
.add(RValue::get(EnforceType(Builder
, Receiver
, IdTy
)), ASTIdTy
);
2666 ActualArgs
.add(RValue::get(cmd
), CGF
.getContext().getObjCSelType());
2667 ActualArgs
.addFrom(CallArgs
);
2669 MessageSendInfo MSI
= getMessageSendInfo(Method
, ResultType
, ActualArgs
);
2671 llvm::Value
*ReceiverClass
= nullptr;
2672 bool isV2ABI
= isRuntime(ObjCRuntime::GNUstep
, 2);
2674 ReceiverClass
= GetClassNamed(CGF
,
2675 Class
->getSuperClass()->getNameAsString(), /*isWeak*/false);
2676 if (IsClassMessage
) {
2677 // Load the isa pointer of the superclass is this is a class method.
2678 ReceiverClass
= Builder
.CreateBitCast(ReceiverClass
,
2679 llvm::PointerType::getUnqual(IdTy
));
2681 Builder
.CreateAlignedLoad(IdTy
, ReceiverClass
, CGF
.getPointerAlign());
2683 ReceiverClass
= EnforceType(Builder
, ReceiverClass
, IdTy
);
2685 if (isCategoryImpl
) {
2686 llvm::FunctionCallee classLookupFunction
= nullptr;
2687 if (IsClassMessage
) {
2688 classLookupFunction
= CGM
.CreateRuntimeFunction(llvm::FunctionType::get(
2689 IdTy
, PtrTy
, true), "objc_get_meta_class");
2691 classLookupFunction
= CGM
.CreateRuntimeFunction(llvm::FunctionType::get(
2692 IdTy
, PtrTy
, true), "objc_get_class");
2694 ReceiverClass
= Builder
.CreateCall(classLookupFunction
,
2695 MakeConstantString(Class
->getNameAsString()));
2697 // Set up global aliases for the metaclass or class pointer if they do not
2698 // already exist. These will are forward-references which will be set to
2699 // pointers to the class and metaclass structure created for the runtime
2700 // load function. To send a message to super, we look up the value of the
2701 // super_class pointer from either the class or metaclass structure.
2702 if (IsClassMessage
) {
2703 if (!MetaClassPtrAlias
) {
2704 MetaClassPtrAlias
= llvm::GlobalAlias::create(
2705 IdElemTy
, 0, llvm::GlobalValue::InternalLinkage
,
2706 ".objc_metaclass_ref" + Class
->getNameAsString(), &TheModule
);
2708 ReceiverClass
= MetaClassPtrAlias
;
2710 if (!ClassPtrAlias
) {
2711 ClassPtrAlias
= llvm::GlobalAlias::create(
2712 IdElemTy
, 0, llvm::GlobalValue::InternalLinkage
,
2713 ".objc_class_ref" + Class
->getNameAsString(), &TheModule
);
2715 ReceiverClass
= ClassPtrAlias
;
2718 // Cast the pointer to a simplified version of the class structure
2719 llvm::Type
*CastTy
= llvm::StructType::get(IdTy
, IdTy
);
2720 ReceiverClass
= Builder
.CreateBitCast(ReceiverClass
,
2721 llvm::PointerType::getUnqual(CastTy
));
2722 // Get the superclass pointer
2723 ReceiverClass
= Builder
.CreateStructGEP(CastTy
, ReceiverClass
, 1);
2724 // Load the superclass pointer
2726 Builder
.CreateAlignedLoad(IdTy
, ReceiverClass
, CGF
.getPointerAlign());
2728 // Construct the structure used to look up the IMP
2729 llvm::StructType
*ObjCSuperTy
=
2730 llvm::StructType::get(Receiver
->getType(), IdTy
);
2732 Address ObjCSuper
= CGF
.CreateTempAlloca(ObjCSuperTy
,
2733 CGF
.getPointerAlign());
2735 Builder
.CreateStore(Receiver
, Builder
.CreateStructGEP(ObjCSuper
, 0));
2736 Builder
.CreateStore(ReceiverClass
, Builder
.CreateStructGEP(ObjCSuper
, 1));
2739 llvm::Value
*imp
= LookupIMPSuper(CGF
, ObjCSuper
, cmd
, MSI
);
2740 imp
= EnforceType(Builder
, imp
, MSI
.MessengerType
);
2742 llvm::Metadata
*impMD
[] = {
2743 llvm::MDString::get(VMContext
, Sel
.getAsString()),
2744 llvm::MDString::get(VMContext
, Class
->getSuperClass()->getNameAsString()),
2745 llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
2746 llvm::Type::getInt1Ty(VMContext
), IsClassMessage
))};
2747 llvm::MDNode
*node
= llvm::MDNode::get(VMContext
, impMD
);
2749 CGCallee
callee(CGCalleeInfo(), imp
);
2751 llvm::CallBase
*call
;
2752 RValue msgRet
= CGF
.EmitCall(MSI
.CallInfo
, callee
, Return
, ActualArgs
, &call
);
2753 call
->setMetadata(msgSendMDKind
, node
);
2757 /// Generate code for a message send expression.
2759 CGObjCGNU::GenerateMessageSend(CodeGenFunction
&CGF
,
2760 ReturnValueSlot Return
,
2761 QualType ResultType
,
2763 llvm::Value
*Receiver
,
2764 const CallArgList
&CallArgs
,
2765 const ObjCInterfaceDecl
*Class
,
2766 const ObjCMethodDecl
*Method
) {
2767 CGBuilderTy
&Builder
= CGF
.Builder
;
2769 // Strip out message sends to retain / release in GC mode
2770 if (CGM
.getLangOpts().getGC() == LangOptions::GCOnly
) {
2771 if (Sel
== RetainSel
|| Sel
== AutoreleaseSel
) {
2772 return RValue::get(EnforceType(Builder
, Receiver
,
2773 CGM
.getTypes().ConvertType(ResultType
)));
2775 if (Sel
== ReleaseSel
) {
2776 return RValue::get(nullptr);
2780 bool isDirect
= Method
&& Method
->isDirectMethod();
2782 IdTy
= cast
<llvm::PointerType
>(CGM
.getTypes().ConvertType(ASTIdTy
));
2786 cmd
= GetSelector(CGF
, Method
);
2788 cmd
= GetSelector(CGF
, Sel
);
2789 cmd
= EnforceType(Builder
, cmd
, SelectorTy
);
2792 Receiver
= EnforceType(Builder
, Receiver
, IdTy
);
2794 llvm::Metadata
*impMD
[] = {
2795 llvm::MDString::get(VMContext
, Sel
.getAsString()),
2796 llvm::MDString::get(VMContext
, Class
? Class
->getNameAsString() : ""),
2797 llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
2798 llvm::Type::getInt1Ty(VMContext
), Class
!= nullptr))};
2799 llvm::MDNode
*node
= llvm::MDNode::get(VMContext
, impMD
);
2801 CallArgList ActualArgs
;
2802 ActualArgs
.add(RValue::get(Receiver
), ASTIdTy
);
2804 ActualArgs
.add(RValue::get(cmd
), CGF
.getContext().getObjCSelType());
2805 ActualArgs
.addFrom(CallArgs
);
2807 MessageSendInfo MSI
= getMessageSendInfo(Method
, ResultType
, ActualArgs
);
2809 // Message sends are expected to return a zero value when the
2810 // receiver is nil. At one point, this was only guaranteed for
2811 // simple integer and pointer types, but expectations have grown
2814 // Given a nil receiver, the GNU runtime's message lookup will
2815 // return a stub function that simply sets various return-value
2816 // registers to zero and then returns. That's good enough for us
2817 // if and only if (1) the calling conventions of that stub are
2818 // compatible with the signature we're using and (2) the registers
2819 // it sets are sufficient to produce a zero value of the return type.
2820 // Rather than doing a whole target-specific analysis, we assume it
2821 // only works for void, integer, and pointer types, and in all
2822 // other cases we do an explicit nil check is emitted code. In
2823 // addition to ensuring we produce a zero value for other types, this
2824 // sidesteps the few outright CC incompatibilities we know about that
2825 // could otherwise lead to crashes, like when a method is expected to
2826 // return on the x87 floating point stack or adjust the stack pointer
2827 // because of an indirect return.
2828 bool hasParamDestroyedInCallee
= false;
2829 bool requiresExplicitZeroResult
= false;
2830 bool requiresNilReceiverCheck
= [&] {
2831 // We never need a check if we statically know the receiver isn't nil.
2832 if (!canMessageReceiverBeNull(CGF
, Method
, /*IsSuper*/ false,
2836 // If there's a consumed argument, we need a nil check.
2837 if (Method
&& Method
->hasParamDestroyedInCallee()) {
2838 hasParamDestroyedInCallee
= true;
2841 // If the return value isn't flagged as unused, and the result
2842 // type isn't in our narrow set where we assume compatibility,
2843 // we need a nil check to ensure a nil value.
2844 if (!Return
.isUnused()) {
2845 if (ResultType
->isVoidType()) {
2846 // void results are definitely okay.
2847 } else if (ResultType
->hasPointerRepresentation() &&
2848 CGM
.getTypes().isZeroInitializable(ResultType
)) {
2849 // Pointer types should be fine as long as they have
2850 // bitwise-zero null pointers. But do we need to worry
2851 // about unusual address spaces?
2852 } else if (ResultType
->isIntegralOrEnumerationType()) {
2853 // Bitwise zero should always be zero for integral types.
2854 // FIXME: we probably need a size limit here, but we've
2855 // never imposed one before
2857 // Otherwise, use an explicit check just to be sure, unless we're
2858 // calling a direct method, where the implementation does this for us.
2859 requiresExplicitZeroResult
= !isDirect
;
2863 return hasParamDestroyedInCallee
|| requiresExplicitZeroResult
;
2866 // We will need to explicitly zero-initialize an aggregate result slot
2867 // if we generally require explicit zeroing and we have an aggregate
2869 bool requiresExplicitAggZeroing
=
2870 requiresExplicitZeroResult
&& CGF
.hasAggregateEvaluationKind(ResultType
);
2872 // The block we're going to end up in after any message send or nil path.
2873 llvm::BasicBlock
*continueBB
= nullptr;
2874 // The block that eventually branched to continueBB along the nil path.
2875 llvm::BasicBlock
*nilPathBB
= nullptr;
2876 // The block to do explicit work in along the nil path, if necessary.
2877 llvm::BasicBlock
*nilCleanupBB
= nullptr;
2879 // Emit the nil-receiver check.
2880 if (requiresNilReceiverCheck
) {
2881 llvm::BasicBlock
*messageBB
= CGF
.createBasicBlock("msgSend");
2882 continueBB
= CGF
.createBasicBlock("continue");
2884 // If we need to zero-initialize an aggregate result or destroy
2885 // consumed arguments, we'll need a separate cleanup block.
2886 // Otherwise we can just branch directly to the continuation block.
2887 if (requiresExplicitAggZeroing
|| hasParamDestroyedInCallee
) {
2888 nilCleanupBB
= CGF
.createBasicBlock("nilReceiverCleanup");
2890 nilPathBB
= Builder
.GetInsertBlock();
2893 llvm::Value
*isNil
= Builder
.CreateICmpEQ(Receiver
,
2894 llvm::Constant::getNullValue(Receiver
->getType()));
2895 Builder
.CreateCondBr(isNil
, nilCleanupBB
? nilCleanupBB
: continueBB
,
2897 CGF
.EmitBlock(messageBB
);
2900 // Get the IMP to call
2903 // If this is a direct method, just emit it here.
2905 imp
= GenerateMethod(Method
, Method
->getClassInterface());
2907 // If we have non-legacy dispatch specified, we try using the
2908 // objc_msgSend() functions. These are not supported on all platforms
2909 // (or all runtimes on a given platform), so we
2910 switch (CGM
.getCodeGenOpts().getObjCDispatchMethod()) {
2911 case CodeGenOptions::Legacy
:
2912 imp
= LookupIMP(CGF
, Receiver
, cmd
, node
, MSI
);
2914 case CodeGenOptions::Mixed
:
2915 case CodeGenOptions::NonLegacy
:
2916 StringRef name
= "objc_msgSend";
2917 if (CGM
.ReturnTypeUsesFPRet(ResultType
)) {
2918 name
= "objc_msgSend_fpret";
2919 } else if (CGM
.ReturnTypeUsesSRet(MSI
.CallInfo
)) {
2920 name
= "objc_msgSend_stret";
2922 // The address of the memory block is be passed in x8 for POD type,
2923 // or in x0 for non-POD type (marked as inreg).
2924 bool shouldCheckForInReg
=
2928 .isWindowsMSVCEnvironment() &&
2929 CGM
.getContext().getTargetInfo().getTriple().isAArch64();
2930 if (shouldCheckForInReg
&& CGM
.ReturnTypeHasInReg(MSI
.CallInfo
)) {
2931 name
= "objc_msgSend_stret2";
2934 // The actual types here don't matter - we're going to bitcast the
2936 imp
= CGM
.CreateRuntimeFunction(llvm::FunctionType::get(IdTy
, IdTy
, true),
2941 // Reset the receiver in case the lookup modified it
2942 ActualArgs
[0] = CallArg(RValue::get(Receiver
), ASTIdTy
);
2944 imp
= EnforceType(Builder
, imp
, MSI
.MessengerType
);
2946 llvm::CallBase
*call
;
2947 CGCallee
callee(CGCalleeInfo(), imp
);
2948 RValue msgRet
= CGF
.EmitCall(MSI
.CallInfo
, callee
, Return
, ActualArgs
, &call
);
2950 call
->setMetadata(msgSendMDKind
, node
);
2952 if (requiresNilReceiverCheck
) {
2953 llvm::BasicBlock
*nonNilPathBB
= CGF
.Builder
.GetInsertBlock();
2954 CGF
.Builder
.CreateBr(continueBB
);
2956 // Emit the nil path if we decided it was necessary above.
2958 CGF
.EmitBlock(nilCleanupBB
);
2960 if (hasParamDestroyedInCallee
) {
2961 destroyCalleeDestroyedArguments(CGF
, Method
, CallArgs
);
2964 if (requiresExplicitAggZeroing
) {
2965 assert(msgRet
.isAggregate());
2966 Address addr
= msgRet
.getAggregateAddress();
2967 CGF
.EmitNullInitialization(addr
, ResultType
);
2970 nilPathBB
= CGF
.Builder
.GetInsertBlock();
2971 CGF
.Builder
.CreateBr(continueBB
);
2974 // Enter the continuation block and emit a phi if required.
2975 CGF
.EmitBlock(continueBB
);
2976 if (msgRet
.isScalar()) {
2977 // If the return type is void, do nothing
2978 if (llvm::Value
*v
= msgRet
.getScalarVal()) {
2979 llvm::PHINode
*phi
= Builder
.CreatePHI(v
->getType(), 2);
2980 phi
->addIncoming(v
, nonNilPathBB
);
2981 phi
->addIncoming(CGM
.EmitNullConstant(ResultType
), nilPathBB
);
2982 msgRet
= RValue::get(phi
);
2984 } else if (msgRet
.isAggregate()) {
2985 // Aggregate zeroing is handled in nilCleanupBB when it's required.
2986 } else /* isComplex() */ {
2987 std::pair
<llvm::Value
*,llvm::Value
*> v
= msgRet
.getComplexVal();
2988 llvm::PHINode
*phi
= Builder
.CreatePHI(v
.first
->getType(), 2);
2989 phi
->addIncoming(v
.first
, nonNilPathBB
);
2990 phi
->addIncoming(llvm::Constant::getNullValue(v
.first
->getType()),
2992 llvm::PHINode
*phi2
= Builder
.CreatePHI(v
.second
->getType(), 2);
2993 phi2
->addIncoming(v
.second
, nonNilPathBB
);
2994 phi2
->addIncoming(llvm::Constant::getNullValue(v
.second
->getType()),
2996 msgRet
= RValue::getComplex(phi
, phi2
);
3002 /// Generates a MethodList. Used in construction of a objc_class and
3003 /// objc_category structures.
3004 llvm::Constant
*CGObjCGNU::
3005 GenerateMethodList(StringRef ClassName
,
3006 StringRef CategoryName
,
3007 ArrayRef
<const ObjCMethodDecl
*> Methods
,
3008 bool isClassMethodList
) {
3009 if (Methods
.empty())
3012 ConstantInitBuilder
Builder(CGM
);
3014 auto MethodList
= Builder
.beginStruct();
3015 MethodList
.addNullPointer(CGM
.Int8PtrTy
);
3016 MethodList
.addInt(Int32Ty
, Methods
.size());
3018 // Get the method structure type.
3019 llvm::StructType
*ObjCMethodTy
=
3020 llvm::StructType::get(CGM
.getLLVMContext(), {
3021 PtrToInt8Ty
, // Really a selector, but the runtime creates it us.
3022 PtrToInt8Ty
, // Method types
3023 IMPTy
// Method pointer
3025 bool isV2ABI
= isRuntime(ObjCRuntime::GNUstep
, 2);
3028 const llvm::DataLayout
&DL
= TheModule
.getDataLayout();
3029 MethodList
.addInt(SizeTy
, DL
.getTypeSizeInBits(ObjCMethodTy
) /
3030 CGM
.getContext().getCharWidth());
3032 llvm::StructType::get(CGM
.getLLVMContext(), {
3033 IMPTy
, // Method pointer
3034 PtrToInt8Ty
, // Selector
3035 PtrToInt8Ty
// Extended type encoding
3039 llvm::StructType::get(CGM
.getLLVMContext(), {
3040 PtrToInt8Ty
, // Really a selector, but the runtime creates it us.
3041 PtrToInt8Ty
, // Method types
3042 IMPTy
// Method pointer
3045 auto MethodArray
= MethodList
.beginArray();
3046 ASTContext
&Context
= CGM
.getContext();
3047 for (const auto *OMD
: Methods
) {
3048 llvm::Constant
*FnPtr
=
3049 TheModule
.getFunction(getSymbolNameForMethod(OMD
));
3050 assert(FnPtr
&& "Can't generate metadata for method that doesn't exist");
3051 auto Method
= MethodArray
.beginStruct(ObjCMethodTy
);
3054 Method
.add(GetConstantSelector(OMD
->getSelector(),
3055 Context
.getObjCEncodingForMethodDecl(OMD
)));
3056 Method
.add(MakeConstantString(Context
.getObjCEncodingForMethodDecl(OMD
, true)));
3058 Method
.add(MakeConstantString(OMD
->getSelector().getAsString()));
3059 Method
.add(MakeConstantString(Context
.getObjCEncodingForMethodDecl(OMD
)));
3062 Method
.finishAndAddTo(MethodArray
);
3064 MethodArray
.finishAndAddTo(MethodList
);
3066 // Create an instance of the structure
3067 return MethodList
.finishAndCreateGlobal(".objc_method_list",
3068 CGM
.getPointerAlign());
3071 /// Generates an IvarList. Used in construction of a objc_class.
3072 llvm::Constant
*CGObjCGNU::
3073 GenerateIvarList(ArrayRef
<llvm::Constant
*> IvarNames
,
3074 ArrayRef
<llvm::Constant
*> IvarTypes
,
3075 ArrayRef
<llvm::Constant
*> IvarOffsets
,
3076 ArrayRef
<llvm::Constant
*> IvarAlign
,
3077 ArrayRef
<Qualifiers::ObjCLifetime
> IvarOwnership
) {
3078 if (IvarNames
.empty())
3081 ConstantInitBuilder
Builder(CGM
);
3083 // Structure containing array count followed by array.
3084 auto IvarList
= Builder
.beginStruct();
3085 IvarList
.addInt(IntTy
, (int)IvarNames
.size());
3087 // Get the ivar structure type.
3088 llvm::StructType
*ObjCIvarTy
=
3089 llvm::StructType::get(PtrToInt8Ty
, PtrToInt8Ty
, IntTy
);
3091 // Array of ivar structures.
3092 auto Ivars
= IvarList
.beginArray(ObjCIvarTy
);
3093 for (unsigned int i
= 0, e
= IvarNames
.size() ; i
< e
; i
++) {
3094 auto Ivar
= Ivars
.beginStruct(ObjCIvarTy
);
3095 Ivar
.add(IvarNames
[i
]);
3096 Ivar
.add(IvarTypes
[i
]);
3097 Ivar
.add(IvarOffsets
[i
]);
3098 Ivar
.finishAndAddTo(Ivars
);
3100 Ivars
.finishAndAddTo(IvarList
);
3102 // Create an instance of the structure
3103 return IvarList
.finishAndCreateGlobal(".objc_ivar_list",
3104 CGM
.getPointerAlign());
3107 /// Generate a class structure
3108 llvm::Constant
*CGObjCGNU::GenerateClassStructure(
3109 llvm::Constant
*MetaClass
,
3110 llvm::Constant
*SuperClass
,
3113 llvm::Constant
*Version
,
3114 llvm::Constant
*InstanceSize
,
3115 llvm::Constant
*IVars
,
3116 llvm::Constant
*Methods
,
3117 llvm::Constant
*Protocols
,
3118 llvm::Constant
*IvarOffsets
,
3119 llvm::Constant
*Properties
,
3120 llvm::Constant
*StrongIvarBitmap
,
3121 llvm::Constant
*WeakIvarBitmap
,
3123 // Set up the class structure
3124 // Note: Several of these are char*s when they should be ids. This is
3125 // because the runtime performs this translation on load.
3127 // Fields marked New ABI are part of the GNUstep runtime. We emit them
3128 // anyway; the classes will still work with the GNU runtime, they will just
3130 llvm::StructType
*ClassTy
= llvm::StructType::get(
3132 PtrToInt8Ty
, // super_class
3133 PtrToInt8Ty
, // name
3136 LongTy
, // instance_size
3137 IVars
->getType(), // ivars
3138 Methods
->getType(), // methods
3139 // These are all filled in by the runtime, so we pretend
3141 PtrTy
, // subclass_list
3142 PtrTy
, // sibling_class
3144 PtrTy
, // gc_object_type
3146 LongTy
, // abi_version
3147 IvarOffsets
->getType(), // ivar_offsets
3148 Properties
->getType(), // properties
3149 IntPtrTy
, // strong_pointers
3150 IntPtrTy
// weak_pointers
3153 ConstantInitBuilder
Builder(CGM
);
3154 auto Elements
= Builder
.beginStruct(ClassTy
);
3156 // Fill in the structure
3159 Elements
.add(MetaClass
);
3161 Elements
.add(SuperClass
);
3163 Elements
.add(MakeConstantString(Name
, ".class_name"));
3165 Elements
.addInt(LongTy
, 0);
3167 Elements
.addInt(LongTy
, info
);
3170 const llvm::DataLayout
&DL
= TheModule
.getDataLayout();
3171 Elements
.addInt(LongTy
, DL
.getTypeSizeInBits(ClassTy
) /
3172 CGM
.getContext().getCharWidth());
3174 Elements
.add(InstanceSize
);
3176 Elements
.add(IVars
);
3178 Elements
.add(Methods
);
3179 // These are all filled in by the runtime, so we pretend
3181 Elements
.add(NULLPtr
);
3183 Elements
.add(NULLPtr
);
3185 Elements
.add(NULLPtr
);
3187 Elements
.add(Protocols
);
3189 Elements
.add(NULLPtr
);
3191 Elements
.addInt(LongTy
, ClassABIVersion
);
3193 Elements
.add(IvarOffsets
);
3195 Elements
.add(Properties
);
3197 Elements
.add(StrongIvarBitmap
);
3199 Elements
.add(WeakIvarBitmap
);
3200 // Create an instance of the structure
3201 // This is now an externally visible symbol, so that we can speed up class
3202 // messages in the next ABI. We may already have some weak references to
3203 // this, so check and fix them properly.
3204 std::string
ClassSym((isMeta
? "_OBJC_METACLASS_": "_OBJC_CLASS_") +
3206 llvm::GlobalVariable
*ClassRef
= TheModule
.getNamedGlobal(ClassSym
);
3207 llvm::Constant
*Class
=
3208 Elements
.finishAndCreateGlobal(ClassSym
, CGM
.getPointerAlign(), false,
3209 llvm::GlobalValue::ExternalLinkage
);
3211 ClassRef
->replaceAllUsesWith(Class
);
3212 ClassRef
->removeFromParent();
3213 Class
->setName(ClassSym
);
3218 llvm::Constant
*CGObjCGNU::
3219 GenerateProtocolMethodList(ArrayRef
<const ObjCMethodDecl
*> Methods
) {
3220 // Get the method structure type.
3221 llvm::StructType
*ObjCMethodDescTy
=
3222 llvm::StructType::get(CGM
.getLLVMContext(), { PtrToInt8Ty
, PtrToInt8Ty
});
3223 ASTContext
&Context
= CGM
.getContext();
3224 ConstantInitBuilder
Builder(CGM
);
3225 auto MethodList
= Builder
.beginStruct();
3226 MethodList
.addInt(IntTy
, Methods
.size());
3227 auto MethodArray
= MethodList
.beginArray(ObjCMethodDescTy
);
3228 for (auto *M
: Methods
) {
3229 auto Method
= MethodArray
.beginStruct(ObjCMethodDescTy
);
3230 Method
.add(MakeConstantString(M
->getSelector().getAsString()));
3231 Method
.add(MakeConstantString(Context
.getObjCEncodingForMethodDecl(M
)));
3232 Method
.finishAndAddTo(MethodArray
);
3234 MethodArray
.finishAndAddTo(MethodList
);
3235 return MethodList
.finishAndCreateGlobal(".objc_method_list",
3236 CGM
.getPointerAlign());
3239 // Create the protocol list structure used in classes, categories and so on
3241 CGObjCGNU::GenerateProtocolList(ArrayRef
<std::string
> Protocols
) {
3243 ConstantInitBuilder
Builder(CGM
);
3244 auto ProtocolList
= Builder
.beginStruct();
3245 ProtocolList
.add(NULLPtr
);
3246 ProtocolList
.addInt(LongTy
, Protocols
.size());
3248 auto Elements
= ProtocolList
.beginArray(PtrToInt8Ty
);
3249 for (const std::string
*iter
= Protocols
.begin(), *endIter
= Protocols
.end();
3250 iter
!= endIter
; iter
++) {
3251 llvm::Constant
*protocol
= nullptr;
3252 llvm::StringMap
<llvm::Constant
*>::iterator value
=
3253 ExistingProtocols
.find(*iter
);
3254 if (value
== ExistingProtocols
.end()) {
3255 protocol
= GenerateEmptyProtocol(*iter
);
3257 protocol
= value
->getValue();
3259 Elements
.add(protocol
);
3261 Elements
.finishAndAddTo(ProtocolList
);
3262 return ProtocolList
.finishAndCreateGlobal(".objc_protocol_list",
3263 CGM
.getPointerAlign());
3266 llvm::Value
*CGObjCGNU::GenerateProtocolRef(CodeGenFunction
&CGF
,
3267 const ObjCProtocolDecl
*PD
) {
3268 auto protocol
= GenerateProtocolRef(PD
);
3270 CGM
.getTypes().ConvertType(CGM
.getContext().getObjCProtoType());
3271 return CGF
.Builder
.CreateBitCast(protocol
, llvm::PointerType::getUnqual(T
));
3274 llvm::Constant
*CGObjCGNU::GenerateProtocolRef(const ObjCProtocolDecl
*PD
) {
3275 llvm::Constant
*&protocol
= ExistingProtocols
[PD
->getNameAsString()];
3277 GenerateProtocol(PD
);
3278 assert(protocol
&& "Unknown protocol");
3283 CGObjCGNU::GenerateEmptyProtocol(StringRef ProtocolName
) {
3284 llvm::Constant
*ProtocolList
= GenerateProtocolList({});
3285 llvm::Constant
*MethodList
= GenerateProtocolMethodList({});
3286 // Protocols are objects containing lists of the methods implemented and
3287 // protocols adopted.
3288 ConstantInitBuilder
Builder(CGM
);
3289 auto Elements
= Builder
.beginStruct();
3291 // The isa pointer must be set to a magic number so the runtime knows it's
3292 // the correct layout.
3293 Elements
.add(llvm::ConstantExpr::getIntToPtr(
3294 llvm::ConstantInt::get(Int32Ty
, ProtocolVersion
), IdTy
));
3296 Elements
.add(MakeConstantString(ProtocolName
, ".objc_protocol_name"));
3297 Elements
.add(ProtocolList
); /* .protocol_list */
3298 Elements
.add(MethodList
); /* .instance_methods */
3299 Elements
.add(MethodList
); /* .class_methods */
3300 Elements
.add(MethodList
); /* .optional_instance_methods */
3301 Elements
.add(MethodList
); /* .optional_class_methods */
3302 Elements
.add(NULLPtr
); /* .properties */
3303 Elements
.add(NULLPtr
); /* .optional_properties */
3304 return Elements
.finishAndCreateGlobal(SymbolForProtocol(ProtocolName
),
3305 CGM
.getPointerAlign());
3308 void CGObjCGNU::GenerateProtocol(const ObjCProtocolDecl
*PD
) {
3309 if (PD
->isNonRuntimeProtocol())
3312 std::string ProtocolName
= PD
->getNameAsString();
3314 // Use the protocol definition, if there is one.
3315 if (const ObjCProtocolDecl
*Def
= PD
->getDefinition())
3318 SmallVector
<std::string
, 16> Protocols
;
3319 for (const auto *PI
: PD
->protocols())
3320 Protocols
.push_back(PI
->getNameAsString());
3321 SmallVector
<const ObjCMethodDecl
*, 16> InstanceMethods
;
3322 SmallVector
<const ObjCMethodDecl
*, 16> OptionalInstanceMethods
;
3323 for (const auto *I
: PD
->instance_methods())
3324 if (I
->isOptional())
3325 OptionalInstanceMethods
.push_back(I
);
3327 InstanceMethods
.push_back(I
);
3328 // Collect information about class methods:
3329 SmallVector
<const ObjCMethodDecl
*, 16> ClassMethods
;
3330 SmallVector
<const ObjCMethodDecl
*, 16> OptionalClassMethods
;
3331 for (const auto *I
: PD
->class_methods())
3332 if (I
->isOptional())
3333 OptionalClassMethods
.push_back(I
);
3335 ClassMethods
.push_back(I
);
3337 llvm::Constant
*ProtocolList
= GenerateProtocolList(Protocols
);
3338 llvm::Constant
*InstanceMethodList
=
3339 GenerateProtocolMethodList(InstanceMethods
);
3340 llvm::Constant
*ClassMethodList
=
3341 GenerateProtocolMethodList(ClassMethods
);
3342 llvm::Constant
*OptionalInstanceMethodList
=
3343 GenerateProtocolMethodList(OptionalInstanceMethods
);
3344 llvm::Constant
*OptionalClassMethodList
=
3345 GenerateProtocolMethodList(OptionalClassMethods
);
3347 // Property metadata: name, attributes, isSynthesized, setter name, setter
3348 // types, getter name, getter types.
3349 // The isSynthesized value is always set to 0 in a protocol. It exists to
3350 // simplify the runtime library by allowing it to use the same data
3351 // structures for protocol metadata everywhere.
3353 llvm::Constant
*PropertyList
=
3354 GeneratePropertyList(nullptr, PD
, false, false);
3355 llvm::Constant
*OptionalPropertyList
=
3356 GeneratePropertyList(nullptr, PD
, false, true);
3358 // Protocols are objects containing lists of the methods implemented and
3359 // protocols adopted.
3360 // The isa pointer must be set to a magic number so the runtime knows it's
3361 // the correct layout.
3362 ConstantInitBuilder
Builder(CGM
);
3363 auto Elements
= Builder
.beginStruct();
3365 llvm::ConstantExpr::getIntToPtr(
3366 llvm::ConstantInt::get(Int32Ty
, ProtocolVersion
), IdTy
));
3367 Elements
.add(MakeConstantString(ProtocolName
));
3368 Elements
.add(ProtocolList
);
3369 Elements
.add(InstanceMethodList
);
3370 Elements
.add(ClassMethodList
);
3371 Elements
.add(OptionalInstanceMethodList
);
3372 Elements
.add(OptionalClassMethodList
);
3373 Elements
.add(PropertyList
);
3374 Elements
.add(OptionalPropertyList
);
3375 ExistingProtocols
[ProtocolName
] =
3376 Elements
.finishAndCreateGlobal(".objc_protocol", CGM
.getPointerAlign());
3378 void CGObjCGNU::GenerateProtocolHolderCategory() {
3379 // Collect information about instance methods
3381 ConstantInitBuilder
Builder(CGM
);
3382 auto Elements
= Builder
.beginStruct();
3384 const std::string ClassName
= "__ObjC_Protocol_Holder_Ugly_Hack";
3385 const std::string CategoryName
= "AnotherHack";
3386 Elements
.add(MakeConstantString(CategoryName
));
3387 Elements
.add(MakeConstantString(ClassName
));
3388 // Instance method list
3389 Elements
.add(GenerateMethodList(ClassName
, CategoryName
, {}, false));
3390 // Class method list
3391 Elements
.add(GenerateMethodList(ClassName
, CategoryName
, {}, true));
3394 ConstantInitBuilder
ProtocolListBuilder(CGM
);
3395 auto ProtocolList
= ProtocolListBuilder
.beginStruct();
3396 ProtocolList
.add(NULLPtr
);
3397 ProtocolList
.addInt(LongTy
, ExistingProtocols
.size());
3398 auto ProtocolElements
= ProtocolList
.beginArray(PtrTy
);
3399 for (auto iter
= ExistingProtocols
.begin(), endIter
= ExistingProtocols
.end();
3400 iter
!= endIter
; iter
++) {
3401 ProtocolElements
.add(iter
->getValue());
3403 ProtocolElements
.finishAndAddTo(ProtocolList
);
3404 Elements
.add(ProtocolList
.finishAndCreateGlobal(".objc_protocol_list",
3405 CGM
.getPointerAlign()));
3406 Categories
.push_back(
3407 Elements
.finishAndCreateGlobal("", CGM
.getPointerAlign()));
3410 /// Libobjc2 uses a bitfield representation where small(ish) bitfields are
3411 /// stored in a 64-bit value with the low bit set to 1 and the remaining 63
3412 /// bits set to their values, LSB first, while larger ones are stored in a
3413 /// structure of this / form:
3415 /// struct { int32_t length; int32_t values[length]; };
3417 /// The values in the array are stored in host-endian format, with the least
3418 /// significant bit being assumed to come first in the bitfield. Therefore, a
3419 /// bitfield with the 64th bit set will be (int64_t)&{ 2, [0, 1<<31] }, while a
3420 /// bitfield / with the 63rd bit set will be 1<<64.
3421 llvm::Constant
*CGObjCGNU::MakeBitField(ArrayRef
<bool> bits
) {
3422 int bitCount
= bits
.size();
3423 int ptrBits
= CGM
.getDataLayout().getPointerSizeInBits();
3424 if (bitCount
< ptrBits
) {
3426 for (int i
=0 ; i
<bitCount
; ++i
) {
3427 if (bits
[i
]) val
|= 1ULL<<(i
+1);
3429 return llvm::ConstantInt::get(IntPtrTy
, val
);
3431 SmallVector
<llvm::Constant
*, 8> values
;
3433 while (v
< bitCount
) {
3435 for (int i
=0 ; (i
<32) && (v
<bitCount
) ; ++i
) {
3436 if (bits
[v
]) word
|= 1<<i
;
3439 values
.push_back(llvm::ConstantInt::get(Int32Ty
, word
));
3442 ConstantInitBuilder
builder(CGM
);
3443 auto fields
= builder
.beginStruct();
3444 fields
.addInt(Int32Ty
, values
.size());
3445 auto array
= fields
.beginArray();
3446 for (auto *v
: values
) array
.add(v
);
3447 array
.finishAndAddTo(fields
);
3449 llvm::Constant
*GS
=
3450 fields
.finishAndCreateGlobal("", CharUnits::fromQuantity(4));
3451 llvm::Constant
*ptr
= llvm::ConstantExpr::getPtrToInt(GS
, IntPtrTy
);
3455 llvm::Constant
*CGObjCGNU::GenerateCategoryProtocolList(const
3456 ObjCCategoryDecl
*OCD
) {
3457 const auto &RefPro
= OCD
->getReferencedProtocols();
3458 const auto RuntimeProtos
=
3459 GetRuntimeProtocolList(RefPro
.begin(), RefPro
.end());
3460 SmallVector
<std::string
, 16> Protocols
;
3461 for (const auto *PD
: RuntimeProtos
)
3462 Protocols
.push_back(PD
->getNameAsString());
3463 return GenerateProtocolList(Protocols
);
3466 void CGObjCGNU::GenerateCategory(const ObjCCategoryImplDecl
*OCD
) {
3467 const ObjCInterfaceDecl
*Class
= OCD
->getClassInterface();
3468 std::string ClassName
= Class
->getNameAsString();
3469 std::string CategoryName
= OCD
->getNameAsString();
3471 // Collect the names of referenced protocols
3472 const ObjCCategoryDecl
*CatDecl
= OCD
->getCategoryDecl();
3474 ConstantInitBuilder
Builder(CGM
);
3475 auto Elements
= Builder
.beginStruct();
3476 Elements
.add(MakeConstantString(CategoryName
));
3477 Elements
.add(MakeConstantString(ClassName
));
3478 // Instance method list
3479 SmallVector
<ObjCMethodDecl
*, 16> InstanceMethods
;
3480 InstanceMethods
.insert(InstanceMethods
.begin(), OCD
->instmeth_begin(),
3481 OCD
->instmeth_end());
3483 GenerateMethodList(ClassName
, CategoryName
, InstanceMethods
, false));
3485 // Class method list
3487 SmallVector
<ObjCMethodDecl
*, 16> ClassMethods
;
3488 ClassMethods
.insert(ClassMethods
.begin(), OCD
->classmeth_begin(),
3489 OCD
->classmeth_end());
3490 Elements
.add(GenerateMethodList(ClassName
, CategoryName
, ClassMethods
, true));
3493 Elements
.add(GenerateCategoryProtocolList(CatDecl
));
3494 if (isRuntime(ObjCRuntime::GNUstep
, 2)) {
3495 const ObjCCategoryDecl
*Category
=
3496 Class
->FindCategoryDeclaration(OCD
->getIdentifier());
3498 // Instance properties
3499 Elements
.add(GeneratePropertyList(OCD
, Category
, false));
3501 Elements
.add(GeneratePropertyList(OCD
, Category
, true));
3503 Elements
.addNullPointer(PtrTy
);
3504 Elements
.addNullPointer(PtrTy
);
3508 Categories
.push_back(Elements
.finishAndCreateGlobal(
3509 std::string(".objc_category_") + ClassName
+ CategoryName
,
3510 CGM
.getPointerAlign()));
3513 llvm::Constant
*CGObjCGNU::GeneratePropertyList(const Decl
*Container
,
3514 const ObjCContainerDecl
*OCD
,
3515 bool isClassProperty
,
3516 bool protocolOptionalProperties
) {
3518 SmallVector
<const ObjCPropertyDecl
*, 16> Properties
;
3519 llvm::SmallPtrSet
<const IdentifierInfo
*, 16> PropertySet
;
3520 bool isProtocol
= isa
<ObjCProtocolDecl
>(OCD
);
3521 ASTContext
&Context
= CGM
.getContext();
3523 std::function
<void(const ObjCProtocolDecl
*Proto
)> collectProtocolProperties
3524 = [&](const ObjCProtocolDecl
*Proto
) {
3525 for (const auto *P
: Proto
->protocols())
3526 collectProtocolProperties(P
);
3527 for (const auto *PD
: Proto
->properties()) {
3528 if (isClassProperty
!= PD
->isClassProperty())
3530 // Skip any properties that are declared in protocols that this class
3531 // conforms to but are not actually implemented by this class.
3532 if (!isProtocol
&& !Context
.getObjCPropertyImplDeclForPropertyDecl(PD
, Container
))
3534 if (!PropertySet
.insert(PD
->getIdentifier()).second
)
3536 Properties
.push_back(PD
);
3540 if (const ObjCInterfaceDecl
*OID
= dyn_cast
<ObjCInterfaceDecl
>(OCD
))
3541 for (const ObjCCategoryDecl
*ClassExt
: OID
->known_extensions())
3542 for (auto *PD
: ClassExt
->properties()) {
3543 if (isClassProperty
!= PD
->isClassProperty())
3545 PropertySet
.insert(PD
->getIdentifier());
3546 Properties
.push_back(PD
);
3549 for (const auto *PD
: OCD
->properties()) {
3550 if (isClassProperty
!= PD
->isClassProperty())
3552 // If we're generating a list for a protocol, skip optional / required ones
3553 // when generating the other list.
3554 if (isProtocol
&& (protocolOptionalProperties
!= PD
->isOptional()))
3556 // Don't emit duplicate metadata for properties that were already in a
3558 if (!PropertySet
.insert(PD
->getIdentifier()).second
)
3561 Properties
.push_back(PD
);
3564 if (const ObjCInterfaceDecl
*OID
= dyn_cast
<ObjCInterfaceDecl
>(OCD
))
3565 for (const auto *P
: OID
->all_referenced_protocols())
3566 collectProtocolProperties(P
);
3567 else if (const ObjCCategoryDecl
*CD
= dyn_cast
<ObjCCategoryDecl
>(OCD
))
3568 for (const auto *P
: CD
->protocols())
3569 collectProtocolProperties(P
);
3571 auto numProperties
= Properties
.size();
3573 if (numProperties
== 0)
3576 ConstantInitBuilder
builder(CGM
);
3577 auto propertyList
= builder
.beginStruct();
3578 auto properties
= PushPropertyListHeader(propertyList
, numProperties
);
3580 // Add all of the property methods need adding to the method list and to the
3581 // property metadata list.
3582 for (auto *property
: Properties
) {
3583 bool isSynthesized
= false;
3584 bool isDynamic
= false;
3586 auto *propertyImpl
= Context
.getObjCPropertyImplDeclForPropertyDecl(property
, Container
);
3588 isSynthesized
= (propertyImpl
->getPropertyImplementation() ==
3589 ObjCPropertyImplDecl::Synthesize
);
3590 isDynamic
= (propertyImpl
->getPropertyImplementation() ==
3591 ObjCPropertyImplDecl::Dynamic
);
3594 PushProperty(properties
, property
, Container
, isSynthesized
, isDynamic
);
3596 properties
.finishAndAddTo(propertyList
);
3598 return propertyList
.finishAndCreateGlobal(".objc_property_list",
3599 CGM
.getPointerAlign());
3602 void CGObjCGNU::RegisterAlias(const ObjCCompatibleAliasDecl
*OAD
) {
3603 // Get the class declaration for which the alias is specified.
3604 ObjCInterfaceDecl
*ClassDecl
=
3605 const_cast<ObjCInterfaceDecl
*>(OAD
->getClassInterface());
3606 ClassAliases
.emplace_back(ClassDecl
->getNameAsString(),
3607 OAD
->getNameAsString());
3610 void CGObjCGNU::GenerateClass(const ObjCImplementationDecl
*OID
) {
3611 ASTContext
&Context
= CGM
.getContext();
3613 // Get the superclass name.
3614 const ObjCInterfaceDecl
* SuperClassDecl
=
3615 OID
->getClassInterface()->getSuperClass();
3616 std::string SuperClassName
;
3617 if (SuperClassDecl
) {
3618 SuperClassName
= SuperClassDecl
->getNameAsString();
3619 EmitClassRef(SuperClassName
);
3622 // Get the class name
3623 ObjCInterfaceDecl
*ClassDecl
=
3624 const_cast<ObjCInterfaceDecl
*>(OID
->getClassInterface());
3625 std::string ClassName
= ClassDecl
->getNameAsString();
3627 // Emit the symbol that is used to generate linker errors if this class is
3628 // referenced in other modules but not declared.
3629 std::string classSymbolName
= "__objc_class_name_" + ClassName
;
3630 if (auto *symbol
= TheModule
.getGlobalVariable(classSymbolName
)) {
3631 symbol
->setInitializer(llvm::ConstantInt::get(LongTy
, 0));
3633 new llvm::GlobalVariable(TheModule
, LongTy
, false,
3634 llvm::GlobalValue::ExternalLinkage
,
3635 llvm::ConstantInt::get(LongTy
, 0),
3639 // Get the size of instances.
3641 Context
.getASTObjCImplementationLayout(OID
).getSize().getQuantity();
3643 // Collect information about instance variables.
3644 SmallVector
<llvm::Constant
*, 16> IvarNames
;
3645 SmallVector
<llvm::Constant
*, 16> IvarTypes
;
3646 SmallVector
<llvm::Constant
*, 16> IvarOffsets
;
3647 SmallVector
<llvm::Constant
*, 16> IvarAligns
;
3648 SmallVector
<Qualifiers::ObjCLifetime
, 16> IvarOwnership
;
3650 ConstantInitBuilder
IvarOffsetBuilder(CGM
);
3651 auto IvarOffsetValues
= IvarOffsetBuilder
.beginArray(PtrToIntTy
);
3652 SmallVector
<bool, 16> WeakIvars
;
3653 SmallVector
<bool, 16> StrongIvars
;
3655 int superInstanceSize
= !SuperClassDecl
? 0 :
3656 Context
.getASTObjCInterfaceLayout(SuperClassDecl
).getSize().getQuantity();
3657 // For non-fragile ivars, set the instance size to 0 - {the size of just this
3658 // class}. The runtime will then set this to the correct value on load.
3659 if (CGM
.getLangOpts().ObjCRuntime
.isNonFragile()) {
3660 instanceSize
= 0 - (instanceSize
- superInstanceSize
);
3663 for (const ObjCIvarDecl
*IVD
= ClassDecl
->all_declared_ivar_begin(); IVD
;
3664 IVD
= IVD
->getNextIvar()) {
3666 IvarNames
.push_back(MakeConstantString(IVD
->getNameAsString()));
3667 // Get the type encoding for this ivar
3668 std::string TypeStr
;
3669 Context
.getObjCEncodingForType(IVD
->getType(), TypeStr
, IVD
);
3670 IvarTypes
.push_back(MakeConstantString(TypeStr
));
3671 IvarAligns
.push_back(llvm::ConstantInt::get(IntTy
,
3672 Context
.getTypeSize(IVD
->getType())));
3674 uint64_t BaseOffset
= ComputeIvarBaseOffset(CGM
, OID
, IVD
);
3675 uint64_t Offset
= BaseOffset
;
3676 if (CGM
.getLangOpts().ObjCRuntime
.isNonFragile()) {
3677 Offset
= BaseOffset
- superInstanceSize
;
3679 llvm::Constant
*OffsetValue
= llvm::ConstantInt::get(IntTy
, Offset
);
3680 // Create the direct offset value
3681 std::string OffsetName
= "__objc_ivar_offset_value_" + ClassName
+"." +
3682 IVD
->getNameAsString();
3684 llvm::GlobalVariable
*OffsetVar
= TheModule
.getGlobalVariable(OffsetName
);
3686 OffsetVar
->setInitializer(OffsetValue
);
3687 // If this is the real definition, change its linkage type so that
3688 // different modules will use this one, rather than their private
3690 OffsetVar
->setLinkage(llvm::GlobalValue::ExternalLinkage
);
3692 OffsetVar
= new llvm::GlobalVariable(TheModule
, Int32Ty
,
3693 false, llvm::GlobalValue::ExternalLinkage
,
3694 OffsetValue
, OffsetName
);
3695 IvarOffsets
.push_back(OffsetValue
);
3696 IvarOffsetValues
.add(OffsetVar
);
3697 Qualifiers::ObjCLifetime lt
= IVD
->getType().getQualifiers().getObjCLifetime();
3698 IvarOwnership
.push_back(lt
);
3700 case Qualifiers::OCL_Strong
:
3701 StrongIvars
.push_back(true);
3702 WeakIvars
.push_back(false);
3704 case Qualifiers::OCL_Weak
:
3705 StrongIvars
.push_back(false);
3706 WeakIvars
.push_back(true);
3709 StrongIvars
.push_back(false);
3710 WeakIvars
.push_back(false);
3713 llvm::Constant
*StrongIvarBitmap
= MakeBitField(StrongIvars
);
3714 llvm::Constant
*WeakIvarBitmap
= MakeBitField(WeakIvars
);
3715 llvm::GlobalVariable
*IvarOffsetArray
=
3716 IvarOffsetValues
.finishAndCreateGlobal(".ivar.offsets",
3717 CGM
.getPointerAlign());
3719 // Collect information about instance methods
3720 SmallVector
<const ObjCMethodDecl
*, 16> InstanceMethods
;
3721 InstanceMethods
.insert(InstanceMethods
.begin(), OID
->instmeth_begin(),
3722 OID
->instmeth_end());
3724 SmallVector
<const ObjCMethodDecl
*, 16> ClassMethods
;
3725 ClassMethods
.insert(ClassMethods
.begin(), OID
->classmeth_begin(),
3726 OID
->classmeth_end());
3728 llvm::Constant
*Properties
= GeneratePropertyList(OID
, ClassDecl
);
3730 // Collect the names of referenced protocols
3731 auto RefProtocols
= ClassDecl
->protocols();
3732 auto RuntimeProtocols
=
3733 GetRuntimeProtocolList(RefProtocols
.begin(), RefProtocols
.end());
3734 SmallVector
<std::string
, 16> Protocols
;
3735 for (const auto *I
: RuntimeProtocols
)
3736 Protocols
.push_back(I
->getNameAsString());
3738 // Get the superclass pointer.
3739 llvm::Constant
*SuperClass
;
3740 if (!SuperClassName
.empty()) {
3741 SuperClass
= MakeConstantString(SuperClassName
, ".super_class_name");
3743 SuperClass
= llvm::ConstantPointerNull::get(PtrToInt8Ty
);
3745 // Empty vector used to construct empty method lists
3746 SmallVector
<llvm::Constant
*, 1> empty
;
3747 // Generate the method and instance variable lists
3748 llvm::Constant
*MethodList
= GenerateMethodList(ClassName
, "",
3749 InstanceMethods
, false);
3750 llvm::Constant
*ClassMethodList
= GenerateMethodList(ClassName
, "",
3751 ClassMethods
, true);
3752 llvm::Constant
*IvarList
= GenerateIvarList(IvarNames
, IvarTypes
,
3753 IvarOffsets
, IvarAligns
, IvarOwnership
);
3754 // Irrespective of whether we are compiling for a fragile or non-fragile ABI,
3755 // we emit a symbol containing the offset for each ivar in the class. This
3756 // allows code compiled for the non-Fragile ABI to inherit from code compiled
3757 // for the legacy ABI, without causing problems. The converse is also
3758 // possible, but causes all ivar accesses to be fragile.
3760 // Offset pointer for getting at the correct field in the ivar list when
3761 // setting up the alias. These are: The base address for the global, the
3762 // ivar array (second field), the ivar in this list (set for each ivar), and
3763 // the offset (third field in ivar structure)
3764 llvm::Type
*IndexTy
= Int32Ty
;
3765 llvm::Constant
*offsetPointerIndexes
[] = {Zeros
[0],
3766 llvm::ConstantInt::get(IndexTy
, ClassABIVersion
> 1 ? 2 : 1), nullptr,
3767 llvm::ConstantInt::get(IndexTy
, ClassABIVersion
> 1 ? 3 : 2) };
3769 unsigned ivarIndex
= 0;
3770 for (const ObjCIvarDecl
*IVD
= ClassDecl
->all_declared_ivar_begin(); IVD
;
3771 IVD
= IVD
->getNextIvar()) {
3772 const std::string Name
= GetIVarOffsetVariableName(ClassDecl
, IVD
);
3773 offsetPointerIndexes
[2] = llvm::ConstantInt::get(IndexTy
, ivarIndex
);
3774 // Get the correct ivar field
3775 llvm::Constant
*offsetValue
= llvm::ConstantExpr::getGetElementPtr(
3776 cast
<llvm::GlobalVariable
>(IvarList
)->getValueType(), IvarList
,
3777 offsetPointerIndexes
);
3778 // Get the existing variable, if one exists.
3779 llvm::GlobalVariable
*offset
= TheModule
.getNamedGlobal(Name
);
3781 offset
->setInitializer(offsetValue
);
3782 // If this is the real definition, change its linkage type so that
3783 // different modules will use this one, rather than their private
3785 offset
->setLinkage(llvm::GlobalValue::ExternalLinkage
);
3787 // Add a new alias if there isn't one already.
3788 new llvm::GlobalVariable(TheModule
, offsetValue
->getType(),
3789 false, llvm::GlobalValue::ExternalLinkage
, offsetValue
, Name
);
3792 llvm::Constant
*ZeroPtr
= llvm::ConstantInt::get(IntPtrTy
, 0);
3794 //Generate metaclass for class methods
3795 llvm::Constant
*MetaClassStruct
= GenerateClassStructure(
3796 NULLPtr
, NULLPtr
, 0x12L
, ClassName
.c_str(), nullptr, Zeros
[0],
3797 NULLPtr
, ClassMethodList
, NULLPtr
, NULLPtr
,
3798 GeneratePropertyList(OID
, ClassDecl
, true), ZeroPtr
, ZeroPtr
, true);
3799 CGM
.setGVProperties(cast
<llvm::GlobalValue
>(MetaClassStruct
),
3800 OID
->getClassInterface());
3802 // Generate the class structure
3803 llvm::Constant
*ClassStruct
= GenerateClassStructure(
3804 MetaClassStruct
, SuperClass
, 0x11L
, ClassName
.c_str(), nullptr,
3805 llvm::ConstantInt::get(LongTy
, instanceSize
), IvarList
, MethodList
,
3806 GenerateProtocolList(Protocols
), IvarOffsetArray
, Properties
,
3807 StrongIvarBitmap
, WeakIvarBitmap
);
3808 CGM
.setGVProperties(cast
<llvm::GlobalValue
>(ClassStruct
),
3809 OID
->getClassInterface());
3811 // Resolve the class aliases, if they exist.
3812 if (ClassPtrAlias
) {
3813 ClassPtrAlias
->replaceAllUsesWith(ClassStruct
);
3814 ClassPtrAlias
->eraseFromParent();
3815 ClassPtrAlias
= nullptr;
3817 if (MetaClassPtrAlias
) {
3818 MetaClassPtrAlias
->replaceAllUsesWith(MetaClassStruct
);
3819 MetaClassPtrAlias
->eraseFromParent();
3820 MetaClassPtrAlias
= nullptr;
3823 // Add class structure to list to be added to the symtab later
3824 Classes
.push_back(ClassStruct
);
3827 llvm::Function
*CGObjCGNU::ModuleInitFunction() {
3828 // Only emit an ObjC load function if no Objective-C stuff has been called
3829 if (Classes
.empty() && Categories
.empty() && ConstantStrings
.empty() &&
3830 ExistingProtocols
.empty() && SelectorTable
.empty())
3833 // Add all referenced protocols to a category.
3834 GenerateProtocolHolderCategory();
3836 llvm::StructType
*selStructTy
= dyn_cast
<llvm::StructType
>(SelectorElemTy
);
3838 selStructTy
= llvm::StructType::get(CGM
.getLLVMContext(),
3839 { PtrToInt8Ty
, PtrToInt8Ty
});
3842 // Generate statics list:
3843 llvm::Constant
*statics
= NULLPtr
;
3844 if (!ConstantStrings
.empty()) {
3845 llvm::GlobalVariable
*fileStatics
= [&] {
3846 ConstantInitBuilder
builder(CGM
);
3847 auto staticsStruct
= builder
.beginStruct();
3849 StringRef stringClass
= CGM
.getLangOpts().ObjCConstantStringClass
;
3850 if (stringClass
.empty()) stringClass
= "NXConstantString";
3851 staticsStruct
.add(MakeConstantString(stringClass
,
3852 ".objc_static_class_name"));
3854 auto array
= staticsStruct
.beginArray();
3855 array
.addAll(ConstantStrings
);
3857 array
.finishAndAddTo(staticsStruct
);
3859 return staticsStruct
.finishAndCreateGlobal(".objc_statics",
3860 CGM
.getPointerAlign());
3863 ConstantInitBuilder
builder(CGM
);
3864 auto allStaticsArray
= builder
.beginArray(fileStatics
->getType());
3865 allStaticsArray
.add(fileStatics
);
3866 allStaticsArray
.addNullPointer(fileStatics
->getType());
3868 statics
= allStaticsArray
.finishAndCreateGlobal(".objc_statics_ptr",
3869 CGM
.getPointerAlign());
3872 // Array of classes, categories, and constant objects.
3874 SmallVector
<llvm::GlobalAlias
*, 16> selectorAliases
;
3875 unsigned selectorCount
;
3877 // Pointer to an array of selectors used in this module.
3878 llvm::GlobalVariable
*selectorList
= [&] {
3879 ConstantInitBuilder
builder(CGM
);
3880 auto selectors
= builder
.beginArray(selStructTy
);
3881 auto &table
= SelectorTable
; // MSVC workaround
3882 std::vector
<Selector
> allSelectors
;
3883 for (auto &entry
: table
)
3884 allSelectors
.push_back(entry
.first
);
3885 llvm::sort(allSelectors
);
3887 for (auto &untypedSel
: allSelectors
) {
3888 std::string selNameStr
= untypedSel
.getAsString();
3889 llvm::Constant
*selName
= ExportUniqueString(selNameStr
, ".objc_sel_name");
3891 for (TypedSelector
&sel
: table
[untypedSel
]) {
3892 llvm::Constant
*selectorTypeEncoding
= NULLPtr
;
3893 if (!sel
.first
.empty())
3894 selectorTypeEncoding
=
3895 MakeConstantString(sel
.first
, ".objc_sel_types");
3897 auto selStruct
= selectors
.beginStruct(selStructTy
);
3898 selStruct
.add(selName
);
3899 selStruct
.add(selectorTypeEncoding
);
3900 selStruct
.finishAndAddTo(selectors
);
3902 // Store the selector alias for later replacement
3903 selectorAliases
.push_back(sel
.second
);
3907 // Remember the number of entries in the selector table.
3908 selectorCount
= selectors
.size();
3910 // NULL-terminate the selector list. This should not actually be required,
3911 // because the selector list has a length field. Unfortunately, the GCC
3912 // runtime decides to ignore the length field and expects a NULL terminator,
3913 // and GCC cooperates with this by always setting the length to 0.
3914 auto selStruct
= selectors
.beginStruct(selStructTy
);
3915 selStruct
.add(NULLPtr
);
3916 selStruct
.add(NULLPtr
);
3917 selStruct
.finishAndAddTo(selectors
);
3919 return selectors
.finishAndCreateGlobal(".objc_selector_list",
3920 CGM
.getPointerAlign());
3923 // Now that all of the static selectors exist, create pointers to them.
3924 for (unsigned i
= 0; i
< selectorCount
; ++i
) {
3925 llvm::Constant
*idxs
[] = {
3927 llvm::ConstantInt::get(Int32Ty
, i
)
3929 // FIXME: We're generating redundant loads and stores here!
3930 llvm::Constant
*selPtr
= llvm::ConstantExpr::getGetElementPtr(
3931 selectorList
->getValueType(), selectorList
, idxs
);
3932 selectorAliases
[i
]->replaceAllUsesWith(selPtr
);
3933 selectorAliases
[i
]->eraseFromParent();
3936 llvm::GlobalVariable
*symtab
= [&] {
3937 ConstantInitBuilder
builder(CGM
);
3938 auto symtab
= builder
.beginStruct();
3940 // Number of static selectors
3941 symtab
.addInt(LongTy
, selectorCount
);
3943 symtab
.add(selectorList
);
3945 // Number of classes defined.
3946 symtab
.addInt(CGM
.Int16Ty
, Classes
.size());
3947 // Number of categories defined
3948 symtab
.addInt(CGM
.Int16Ty
, Categories
.size());
3950 // Create an array of classes, then categories, then static object instances
3951 auto classList
= symtab
.beginArray(PtrToInt8Ty
);
3952 classList
.addAll(Classes
);
3953 classList
.addAll(Categories
);
3954 // NULL-terminated list of static object instances (mainly constant strings)
3955 classList
.add(statics
);
3956 classList
.add(NULLPtr
);
3957 classList
.finishAndAddTo(symtab
);
3959 // Construct the symbol table.
3960 return symtab
.finishAndCreateGlobal("", CGM
.getPointerAlign());
3963 // The symbol table is contained in a module which has some version-checking
3965 llvm::Constant
*module
= [&] {
3966 llvm::Type
*moduleEltTys
[] = {
3967 LongTy
, LongTy
, PtrToInt8Ty
, symtab
->getType(), IntTy
3969 llvm::StructType
*moduleTy
= llvm::StructType::get(
3970 CGM
.getLLVMContext(),
3971 ArrayRef(moduleEltTys
).drop_back(unsigned(RuntimeVersion
< 10)));
3973 ConstantInitBuilder
builder(CGM
);
3974 auto module
= builder
.beginStruct(moduleTy
);
3975 // Runtime version, used for ABI compatibility checking.
3976 module
.addInt(LongTy
, RuntimeVersion
);
3978 module
.addInt(LongTy
, CGM
.getDataLayout().getTypeStoreSize(moduleTy
));
3980 // The path to the source file where this module was declared
3981 SourceManager
&SM
= CGM
.getContext().getSourceManager();
3982 OptionalFileEntryRef mainFile
= SM
.getFileEntryRefForID(SM
.getMainFileID());
3984 (mainFile
->getDir().getName() + "/" + mainFile
->getName()).str();
3985 module
.add(MakeConstantString(path
, ".objc_source_file_name"));
3988 if (RuntimeVersion
>= 10) {
3989 switch (CGM
.getLangOpts().getGC()) {
3990 case LangOptions::GCOnly
:
3991 module
.addInt(IntTy
, 2);
3993 case LangOptions::NonGC
:
3994 if (CGM
.getLangOpts().ObjCAutoRefCount
)
3995 module
.addInt(IntTy
, 1);
3997 module
.addInt(IntTy
, 0);
3999 case LangOptions::HybridGC
:
4000 module
.addInt(IntTy
, 1);
4005 return module
.finishAndCreateGlobal("", CGM
.getPointerAlign());
4008 // Create the load function calling the runtime entry point with the module
4010 llvm::Function
* LoadFunction
= llvm::Function::Create(
4011 llvm::FunctionType::get(llvm::Type::getVoidTy(VMContext
), false),
4012 llvm::GlobalValue::InternalLinkage
, ".objc_load_function",
4014 llvm::BasicBlock
*EntryBB
=
4015 llvm::BasicBlock::Create(VMContext
, "entry", LoadFunction
);
4016 CGBuilderTy
Builder(CGM
, VMContext
);
4017 Builder
.SetInsertPoint(EntryBB
);
4019 llvm::FunctionType
*FT
=
4020 llvm::FunctionType::get(Builder
.getVoidTy(), module
->getType(), true);
4021 llvm::FunctionCallee Register
=
4022 CGM
.CreateRuntimeFunction(FT
, "__objc_exec_class");
4023 Builder
.CreateCall(Register
, module
);
4025 if (!ClassAliases
.empty()) {
4026 llvm::Type
*ArgTypes
[2] = {PtrTy
, PtrToInt8Ty
};
4027 llvm::FunctionType
*RegisterAliasTy
=
4028 llvm::FunctionType::get(Builder
.getVoidTy(),
4030 llvm::Function
*RegisterAlias
= llvm::Function::Create(
4032 llvm::GlobalValue::ExternalWeakLinkage
, "class_registerAlias_np",
4034 llvm::BasicBlock
*AliasBB
=
4035 llvm::BasicBlock::Create(VMContext
, "alias", LoadFunction
);
4036 llvm::BasicBlock
*NoAliasBB
=
4037 llvm::BasicBlock::Create(VMContext
, "no_alias", LoadFunction
);
4039 // Branch based on whether the runtime provided class_registerAlias_np()
4040 llvm::Value
*HasRegisterAlias
= Builder
.CreateICmpNE(RegisterAlias
,
4041 llvm::Constant::getNullValue(RegisterAlias
->getType()));
4042 Builder
.CreateCondBr(HasRegisterAlias
, AliasBB
, NoAliasBB
);
4044 // The true branch (has alias registration function):
4045 Builder
.SetInsertPoint(AliasBB
);
4046 // Emit alias registration calls:
4047 for (std::vector
<ClassAliasPair
>::iterator iter
= ClassAliases
.begin();
4048 iter
!= ClassAliases
.end(); ++iter
) {
4049 llvm::Constant
*TheClass
=
4050 TheModule
.getGlobalVariable("_OBJC_CLASS_" + iter
->first
, true);
4052 Builder
.CreateCall(RegisterAlias
,
4053 {TheClass
, MakeConstantString(iter
->second
)});
4057 Builder
.CreateBr(NoAliasBB
);
4059 // Missing alias registration function, just return from the function:
4060 Builder
.SetInsertPoint(NoAliasBB
);
4062 Builder
.CreateRetVoid();
4064 return LoadFunction
;
4067 llvm::Function
*CGObjCGNU::GenerateMethod(const ObjCMethodDecl
*OMD
,
4068 const ObjCContainerDecl
*CD
) {
4069 CodeGenTypes
&Types
= CGM
.getTypes();
4070 llvm::FunctionType
*MethodTy
=
4071 Types
.GetFunctionType(Types
.arrangeObjCMethodDeclaration(OMD
));
4073 bool isDirect
= OMD
->isDirectMethod();
4074 std::string FunctionName
=
4075 getSymbolNameForMethod(OMD
, /*include category*/ !isDirect
);
4078 return llvm::Function::Create(MethodTy
,
4079 llvm::GlobalVariable::InternalLinkage
,
4080 FunctionName
, &TheModule
);
4082 auto *COMD
= OMD
->getCanonicalDecl();
4083 auto I
= DirectMethodDefinitions
.find(COMD
);
4084 llvm::Function
*OldFn
= nullptr, *Fn
= nullptr;
4086 if (I
== DirectMethodDefinitions
.end()) {
4088 llvm::Function::Create(MethodTy
, llvm::GlobalVariable::ExternalLinkage
,
4089 FunctionName
, &TheModule
);
4090 DirectMethodDefinitions
.insert(std::make_pair(COMD
, F
));
4094 // Objective-C allows for the declaration and implementation types
4095 // to differ slightly.
4097 // If we're being asked for the Function associated for a method
4098 // implementation, a previous value might have been cached
4099 // based on the type of the canonical declaration.
4101 // If these do not match, then we'll replace this function with
4102 // a new one that has the proper type below.
4103 if (!OMD
->getBody() || COMD
->getReturnType() == OMD
->getReturnType())
4107 Fn
= llvm::Function::Create(MethodTy
, llvm::GlobalValue::ExternalLinkage
, "",
4109 Fn
->takeName(OldFn
);
4110 OldFn
->replaceAllUsesWith(Fn
);
4111 OldFn
->eraseFromParent();
4113 // Replace the cached function in the map.
4118 void CGObjCGNU::GenerateDirectMethodPrologue(CodeGenFunction
&CGF
,
4120 const ObjCMethodDecl
*OMD
,
4121 const ObjCContainerDecl
*CD
) {
4122 // GNU runtime doesn't support direct calls at this time
4125 llvm::FunctionCallee
CGObjCGNU::GetPropertyGetFunction() {
4126 return GetPropertyFn
;
4129 llvm::FunctionCallee
CGObjCGNU::GetPropertySetFunction() {
4130 return SetPropertyFn
;
4133 llvm::FunctionCallee
CGObjCGNU::GetOptimizedPropertySetFunction(bool atomic
,
4138 llvm::FunctionCallee
CGObjCGNU::GetGetStructFunction() {
4139 return GetStructPropertyFn
;
4142 llvm::FunctionCallee
CGObjCGNU::GetSetStructFunction() {
4143 return SetStructPropertyFn
;
4146 llvm::FunctionCallee
CGObjCGNU::GetCppAtomicObjectGetFunction() {
4150 llvm::FunctionCallee
CGObjCGNU::GetCppAtomicObjectSetFunction() {
4154 llvm::FunctionCallee
CGObjCGNU::EnumerationMutationFunction() {
4155 return EnumerationMutationFn
;
4158 void CGObjCGNU::EmitSynchronizedStmt(CodeGenFunction
&CGF
,
4159 const ObjCAtSynchronizedStmt
&S
) {
4160 EmitAtSynchronizedStmt(CGF
, S
, SyncEnterFn
, SyncExitFn
);
4164 void CGObjCGNU::EmitTryStmt(CodeGenFunction
&CGF
,
4165 const ObjCAtTryStmt
&S
) {
4166 // Unlike the Apple non-fragile runtimes, which also uses
4167 // unwind-based zero cost exceptions, the GNU Objective C runtime's
4168 // EH support isn't a veneer over C++ EH. Instead, exception
4169 // objects are created by objc_exception_throw and destroyed by
4170 // the personality function; this avoids the need for bracketing
4171 // catch handlers with calls to __blah_begin_catch/__blah_end_catch
4172 // (or even _Unwind_DeleteException), but probably doesn't
4173 // interoperate very well with foreign exceptions.
4175 // In Objective-C++ mode, we actually emit something equivalent to the C++
4176 // exception handler.
4177 EmitTryCatchStmt(CGF
, S
, EnterCatchFn
, ExitCatchFn
, ExceptionReThrowFn
);
4180 void CGObjCGNU::EmitThrowStmt(CodeGenFunction
&CGF
,
4181 const ObjCAtThrowStmt
&S
,
4182 bool ClearInsertionPoint
) {
4183 llvm::Value
*ExceptionAsObject
;
4184 bool isRethrow
= false;
4186 if (const Expr
*ThrowExpr
= S
.getThrowExpr()) {
4187 llvm::Value
*Exception
= CGF
.EmitObjCThrowOperand(ThrowExpr
);
4188 ExceptionAsObject
= Exception
;
4190 assert((!CGF
.ObjCEHValueStack
.empty() && CGF
.ObjCEHValueStack
.back()) &&
4191 "Unexpected rethrow outside @catch block.");
4192 ExceptionAsObject
= CGF
.ObjCEHValueStack
.back();
4195 if (isRethrow
&& (usesSEHExceptions
|| usesCxxExceptions
)) {
4196 // For SEH, ExceptionAsObject may be undef, because the catch handler is
4197 // not passed it for catchalls and so it is not visible to the catch
4198 // funclet. The real thrown object will still be live on the stack at this
4199 // point and will be rethrown. If we are explicitly rethrowing the object
4200 // that was passed into the `@catch` block, then this code path is not
4201 // reached and we will instead call `objc_exception_throw` with an explicit
4203 llvm::CallBase
*Throw
= CGF
.EmitRuntimeCallOrInvoke(ExceptionReThrowFn
);
4204 Throw
->setDoesNotReturn();
4206 ExceptionAsObject
= CGF
.Builder
.CreateBitCast(ExceptionAsObject
, IdTy
);
4207 llvm::CallBase
*Throw
=
4208 CGF
.EmitRuntimeCallOrInvoke(ExceptionThrowFn
, ExceptionAsObject
);
4209 Throw
->setDoesNotReturn();
4211 CGF
.Builder
.CreateUnreachable();
4212 if (ClearInsertionPoint
)
4213 CGF
.Builder
.ClearInsertionPoint();
4216 llvm::Value
* CGObjCGNU::EmitObjCWeakRead(CodeGenFunction
&CGF
,
4217 Address AddrWeakObj
) {
4218 CGBuilderTy
&B
= CGF
.Builder
;
4219 return B
.CreateCall(
4220 WeakReadFn
, EnforceType(B
, AddrWeakObj
.emitRawPointer(CGF
), PtrToIdTy
));
4223 void CGObjCGNU::EmitObjCWeakAssign(CodeGenFunction
&CGF
,
4224 llvm::Value
*src
, Address dst
) {
4225 CGBuilderTy
&B
= CGF
.Builder
;
4226 src
= EnforceType(B
, src
, IdTy
);
4227 llvm::Value
*dstVal
= EnforceType(B
, dst
.emitRawPointer(CGF
), PtrToIdTy
);
4228 B
.CreateCall(WeakAssignFn
, {src
, dstVal
});
4231 void CGObjCGNU::EmitObjCGlobalAssign(CodeGenFunction
&CGF
,
4232 llvm::Value
*src
, Address dst
,
4234 CGBuilderTy
&B
= CGF
.Builder
;
4235 src
= EnforceType(B
, src
, IdTy
);
4236 llvm::Value
*dstVal
= EnforceType(B
, dst
.emitRawPointer(CGF
), PtrToIdTy
);
4237 // FIXME. Add threadloca assign API
4238 assert(!threadlocal
&& "EmitObjCGlobalAssign - Threal Local API NYI");
4239 B
.CreateCall(GlobalAssignFn
, {src
, dstVal
});
4242 void CGObjCGNU::EmitObjCIvarAssign(CodeGenFunction
&CGF
,
4243 llvm::Value
*src
, Address dst
,
4244 llvm::Value
*ivarOffset
) {
4245 CGBuilderTy
&B
= CGF
.Builder
;
4246 src
= EnforceType(B
, src
, IdTy
);
4247 llvm::Value
*dstVal
= EnforceType(B
, dst
.emitRawPointer(CGF
), IdTy
);
4248 B
.CreateCall(IvarAssignFn
, {src
, dstVal
, ivarOffset
});
4251 void CGObjCGNU::EmitObjCStrongCastAssign(CodeGenFunction
&CGF
,
4252 llvm::Value
*src
, Address dst
) {
4253 CGBuilderTy
&B
= CGF
.Builder
;
4254 src
= EnforceType(B
, src
, IdTy
);
4255 llvm::Value
*dstVal
= EnforceType(B
, dst
.emitRawPointer(CGF
), PtrToIdTy
);
4256 B
.CreateCall(StrongCastAssignFn
, {src
, dstVal
});
4259 void CGObjCGNU::EmitGCMemmoveCollectable(CodeGenFunction
&CGF
,
4262 llvm::Value
*Size
) {
4263 CGBuilderTy
&B
= CGF
.Builder
;
4264 llvm::Value
*DestPtrVal
= EnforceType(B
, DestPtr
.emitRawPointer(CGF
), PtrTy
);
4265 llvm::Value
*SrcPtrVal
= EnforceType(B
, SrcPtr
.emitRawPointer(CGF
), PtrTy
);
4267 B
.CreateCall(MemMoveFn
, {DestPtrVal
, SrcPtrVal
, Size
});
4270 llvm::GlobalVariable
*CGObjCGNU::ObjCIvarOffsetVariable(
4271 const ObjCInterfaceDecl
*ID
,
4272 const ObjCIvarDecl
*Ivar
) {
4273 const std::string Name
= GetIVarOffsetVariableName(ID
, Ivar
);
4274 // Emit the variable and initialize it with what we think the correct value
4275 // is. This allows code compiled with non-fragile ivars to work correctly
4276 // when linked against code which isn't (most of the time).
4277 llvm::GlobalVariable
*IvarOffsetPointer
= TheModule
.getNamedGlobal(Name
);
4278 if (!IvarOffsetPointer
)
4279 IvarOffsetPointer
= new llvm::GlobalVariable(
4280 TheModule
, llvm::PointerType::getUnqual(VMContext
), false,
4281 llvm::GlobalValue::ExternalLinkage
, nullptr, Name
);
4282 return IvarOffsetPointer
;
4285 LValue
CGObjCGNU::EmitObjCValueForIvar(CodeGenFunction
&CGF
,
4287 llvm::Value
*BaseValue
,
4288 const ObjCIvarDecl
*Ivar
,
4289 unsigned CVRQualifiers
) {
4290 const ObjCInterfaceDecl
*ID
=
4291 ObjectTy
->castAs
<ObjCObjectType
>()->getInterface();
4292 return EmitValueForIvarAtOffset(CGF
, ID
, BaseValue
, Ivar
, CVRQualifiers
,
4293 EmitIvarOffset(CGF
, ID
, Ivar
));
4296 static const ObjCInterfaceDecl
*FindIvarInterface(ASTContext
&Context
,
4297 const ObjCInterfaceDecl
*OID
,
4298 const ObjCIvarDecl
*OIVD
) {
4299 for (const ObjCIvarDecl
*next
= OID
->all_declared_ivar_begin(); next
;
4300 next
= next
->getNextIvar()) {
4305 // Otherwise check in the super class.
4306 if (const ObjCInterfaceDecl
*Super
= OID
->getSuperClass())
4307 return FindIvarInterface(Context
, Super
, OIVD
);
4312 llvm::Value
*CGObjCGNU::EmitIvarOffset(CodeGenFunction
&CGF
,
4313 const ObjCInterfaceDecl
*Interface
,
4314 const ObjCIvarDecl
*Ivar
) {
4315 if (CGM
.getLangOpts().ObjCRuntime
.isNonFragile()) {
4316 Interface
= FindIvarInterface(CGM
.getContext(), Interface
, Ivar
);
4318 // The MSVC linker cannot have a single global defined as LinkOnceAnyLinkage
4319 // and ExternalLinkage, so create a reference to the ivar global and rely on
4320 // the definition being created as part of GenerateClass.
4321 if (RuntimeVersion
< 10 ||
4322 CGF
.CGM
.getTarget().getTriple().isKnownWindowsMSVCEnvironment())
4323 return CGF
.Builder
.CreateZExtOrBitCast(
4324 CGF
.Builder
.CreateAlignedLoad(
4326 CGF
.Builder
.CreateAlignedLoad(
4327 llvm::PointerType::getUnqual(VMContext
),
4328 ObjCIvarOffsetVariable(Interface
, Ivar
),
4329 CGF
.getPointerAlign(), "ivar"),
4330 CharUnits::fromQuantity(4)),
4332 std::string name
= "__objc_ivar_offset_value_" +
4333 Interface
->getNameAsString() +"." + Ivar
->getNameAsString();
4334 CharUnits Align
= CGM
.getIntAlign();
4335 llvm::Value
*Offset
= TheModule
.getGlobalVariable(name
);
4337 auto GV
= new llvm::GlobalVariable(TheModule
, IntTy
,
4338 false, llvm::GlobalValue::LinkOnceAnyLinkage
,
4339 llvm::Constant::getNullValue(IntTy
), name
);
4340 GV
->setAlignment(Align
.getAsAlign());
4343 Offset
= CGF
.Builder
.CreateAlignedLoad(IntTy
, Offset
, Align
);
4344 if (Offset
->getType() != PtrDiffTy
)
4345 Offset
= CGF
.Builder
.CreateZExtOrBitCast(Offset
, PtrDiffTy
);
4348 uint64_t Offset
= ComputeIvarBaseOffset(CGF
.CGM
, Interface
, Ivar
);
4349 return llvm::ConstantInt::get(PtrDiffTy
, Offset
, /*isSigned*/true);
4353 clang::CodeGen::CreateGNUObjCRuntime(CodeGenModule
&CGM
) {
4354 auto Runtime
= CGM
.getLangOpts().ObjCRuntime
;
4355 switch (Runtime
.getKind()) {
4356 case ObjCRuntime::GNUstep
:
4357 if (Runtime
.getVersion() >= VersionTuple(2, 0))
4358 return new CGObjCGNUstep2(CGM
);
4359 return new CGObjCGNUstep(CGM
);
4361 case ObjCRuntime::GCC
:
4362 return new CGObjCGCC(CGM
);
4364 case ObjCRuntime::ObjFW
:
4365 return new CGObjCObjFW(CGM
);
4367 case ObjCRuntime::FragileMacOSX
:
4368 case ObjCRuntime::MacOSX
:
4369 case ObjCRuntime::iOS
:
4370 case ObjCRuntime::WatchOS
:
4371 llvm_unreachable("these runtimes are not GNU runtimes");
4373 llvm_unreachable("bad runtime");