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