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