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