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