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