1//===----- CGObjCRuntime.h - Interface to ObjC Runtimes ---------*- C++ -*-===//
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 an abstract class for Objective-C code generation. Concrete
10// subclasses of this implement code generation for specific Objective-C
11// runtime libraries.
12//
13//===----------------------------------------------------------------------===//
14
15#ifndef LLVM_CLANG_LIB_CODEGEN_CGOBJCRUNTIME_H
16#define LLVM_CLANG_LIB_CODEGEN_CGOBJCRUNTIME_H
17#include "CGBuilder.h"
18#include "CGCall.h"
19#include "CGCleanup.h"
20#include "CGValue.h"
21#include "clang/AST/DeclObjC.h"
22#include "clang/Basic/IdentifierTable.h" // Selector
23#include "llvm/ADT/UniqueVector.h"
24
25namespace llvm {
26class Constant;
27class Function;
28class Module;
29class StructLayout;
30class StructType;
31class Type;
32class Value;
33} // namespace llvm
34
35namespace clang {
36namespace CodeGen {
37class CGFunctionInfo;
38class CodeGenFunction;
39} // namespace CodeGen
40
41class FieldDecl;
42class ObjCAtTryStmt;
43class ObjCAtThrowStmt;
44class ObjCAtSynchronizedStmt;
45class ObjCContainerDecl;
46class ObjCCategoryImplDecl;
47class ObjCImplementationDecl;
48class ObjCInterfaceDecl;
49class ObjCMessageExpr;
50class ObjCMethodDecl;
51class ObjCProtocolDecl;
52class Selector;
53class ObjCIvarDecl;
54class ObjCStringLiteral;
55
56namespace CodeGen {
57class CodeGenModule;
58class CGBlockInfo;
59
60// FIXME: Several methods should be pure virtual but aren't to avoid the
61// partially-implemented subclass breaking.
62
63/// Implements runtime-specific code generation functions.
64class CGObjCRuntime {
65protected:
66 CodeGen::CodeGenModule &CGM;
67 CGObjCRuntime(CodeGen::CodeGenModule &CGM) : CGM(CGM) {}
68
69 // Utility functions for unified ivar access. These need to
70 // eventually be folded into other places (the structure layout
71 // code).
72
73 /// Compute an offset to the given ivar, suitable for passing to
74 /// EmitValueForIvarAtOffset. Note that the correct handling of
75 /// bit-fields is carefully coordinated by these two, use caution!
76 ///
77 /// The latter overload is suitable for computing the offset of a
78 /// sythesized ivar.
79 uint64_t ComputeIvarBaseOffset(CodeGen::CodeGenModule &CGM,
80 const ObjCInterfaceDecl *OID,
81 const ObjCIvarDecl *Ivar);
82 uint64_t ComputeIvarBaseOffset(CodeGen::CodeGenModule &CGM,
83 const ObjCImplementationDecl *OID,
84 const ObjCIvarDecl *Ivar);
85
86 LValue EmitValueForIvarAtOffset(CodeGen::CodeGenFunction &CGF,
87 const ObjCInterfaceDecl *OID,
88 llvm::Value *BaseValue,
89 const ObjCIvarDecl *Ivar,
90 unsigned CVRQualifiers, llvm::Value *Offset);
91 /// Emits a try / catch statement. This function is intended to be called by
92 /// subclasses, and provides a generic mechanism for generating these, which
93 /// should be usable by all runtimes. The caller must provide the functions
94 /// to call when entering and exiting a \@catch() block, and the function
95 /// used to rethrow exceptions. If the begin and end catch functions are
96 /// NULL, then the function assumes that the EH personality function provides
97 /// the thrown object directly.
98 void EmitTryCatchStmt(CodeGenFunction &CGF, const ObjCAtTryStmt &S,
99 llvm::FunctionCallee beginCatchFn,
100 llvm::FunctionCallee endCatchFn,
101 llvm::FunctionCallee exceptionRethrowFn);
102
103 void EmitInitOfCatchParam(CodeGenFunction &CGF, llvm::Value *exn,
104 const VarDecl *paramDecl);
105
106 /// Emits an \@synchronize() statement, using the \p syncEnterFn and
107 /// \p syncExitFn arguments as the functions called to lock and unlock
108 /// the object. This function can be called by subclasses that use
109 /// zero-cost exception handling.
110 void EmitAtSynchronizedStmt(CodeGenFunction &CGF,
111 const ObjCAtSynchronizedStmt &S,
112 llvm::FunctionCallee syncEnterFn,
113 llvm::FunctionCallee syncExitFn);
114
115public:
116 virtual ~CGObjCRuntime();
117
118 std::string getSymbolNameForMethod(const ObjCMethodDecl *method,
119 bool includeCategoryName = true,
120 bool useDirectABI = false);
121
122 /// Generate the function required to register all Objective-C components in
123 /// this compilation unit with the runtime library.
124 virtual llvm::Function *ModuleInitFunction() = 0;
125
126 /// Get a selector for the specified name and type values.
127 /// The result should have the LLVM type for ASTContext::getObjCSelType().
128 virtual llvm::Value *GetSelector(CodeGenFunction &CGF, Selector Sel) = 0;
129
130 /// Get the address of a selector for the specified name and type values.
131 /// This is a rarely-used language extension, but sadly it exists.
132 ///
133 /// The result should have the LLVM type for a pointer to
134 /// ASTContext::getObjCSelType().
135 virtual Address GetAddrOfSelector(CodeGenFunction &CGF, Selector Sel) = 0;
136
137 /// Get a typed selector.
138 virtual llvm::Value *GetSelector(CodeGenFunction &CGF,
139 const ObjCMethodDecl *Method) = 0;
140
141 /// Get the type constant to catch for the given ObjC pointer type.
142 /// This is used externally to implement catching ObjC types in C++.
143 /// Runtimes which don't support this should add the appropriate
144 /// error to Sema.
145 virtual llvm::Constant *GetEHType(QualType T) = 0;
146
147 virtual CatchTypeInfo getCatchAllTypeInfo() { return {.RTTI: nullptr, .Flags: 0}; }
148
149 /// Generate a constant string object.
150 virtual ConstantAddress GenerateConstantString(const StringLiteral *) = 0;
151 virtual ConstantAddress GenerateConstantNumber(const bool Value,
152 const QualType &Ty) = 0;
153 virtual ConstantAddress GenerateConstantNumber(const llvm::APSInt &Value,
154 const QualType &Ty) = 0;
155 virtual ConstantAddress GenerateConstantNumber(const llvm::APFloat &Value,
156 const QualType &Ty) = 0;
157 virtual ConstantAddress
158 GenerateConstantArray(const ArrayRef<llvm::Constant *> &Objects) = 0;
159 virtual ConstantAddress GenerateConstantDictionary(
160 const ObjCDictionaryLiteral *E,
161 ArrayRef<std::pair<llvm::Constant *, llvm::Constant *>>
162 KeysAndObjects) = 0;
163
164 /// Generate a category. A category contains a list of methods (and
165 /// accompanying metadata) and a list of protocols.
166 virtual void GenerateCategory(const ObjCCategoryImplDecl *OCD) = 0;
167
168 /// Generate a class structure for this class.
169 virtual void GenerateClass(const ObjCImplementationDecl *OID) = 0;
170
171 /// Register an class alias.
172 virtual void RegisterAlias(const ObjCCompatibleAliasDecl *OAD) = 0;
173
174 /// Generate an Objective-C message send operation.
175 ///
176 /// \param Method - The method being called, this may be null if synthesizing
177 /// a property setter or getter.
178 virtual CodeGen::RValue
179 GenerateMessageSend(CodeGen::CodeGenFunction &CGF, ReturnValueSlot ReturnSlot,
180 QualType ResultType, Selector Sel, llvm::Value *Receiver,
181 const CallArgList &CallArgs,
182 const ObjCInterfaceDecl *Class = nullptr,
183 const ObjCMethodDecl *Method = nullptr) = 0;
184
185 /// Generate an Objective-C message send operation.
186 ///
187 /// This variant allows for the call to be substituted with an optimized
188 /// variant.
189 CodeGen::RValue GeneratePossiblySpecializedMessageSend(
190 CodeGenFunction &CGF, ReturnValueSlot Return, QualType ResultType,
191 Selector Sel, llvm::Value *Receiver, const CallArgList &Args,
192 const ObjCInterfaceDecl *OID, const ObjCMethodDecl *Method,
193 bool isClassMessage);
194
195 /// Generate an Objective-C message send operation to the super
196 /// class initiated in a method for Class and with the given Self
197 /// object.
198 ///
199 /// \param Method - The method being called, this may be null if synthesizing
200 /// a property setter or getter.
201 virtual CodeGen::RValue GenerateMessageSendSuper(
202 CodeGen::CodeGenFunction &CGF, ReturnValueSlot ReturnSlot,
203 QualType ResultType, Selector Sel, const ObjCInterfaceDecl *Class,
204 bool isCategoryImpl, llvm::Value *Self, bool IsClassMessage,
205 const CallArgList &CallArgs, const ObjCMethodDecl *Method = nullptr) = 0;
206
207 /// Walk the list of protocol references from a class, category or
208 /// protocol to traverse the DAG formed from it's inheritance hierarchy. Find
209 /// the list of protocols that ends each walk at either a runtime
210 /// protocol or a non-runtime protocol with no parents. For the common case of
211 /// just a list of standard runtime protocols this just returns the same list
212 /// that was passed in.
213 std::vector<const ObjCProtocolDecl *>
214 GetRuntimeProtocolList(ObjCProtocolDecl::protocol_iterator begin,
215 ObjCProtocolDecl::protocol_iterator end);
216
217 /// Emit the code to return the named protocol as an object, as in a
218 /// \@protocol expression.
219 virtual llvm::Value *GenerateProtocolRef(CodeGenFunction &CGF,
220 const ObjCProtocolDecl *OPD) = 0;
221
222 /// Generate the named protocol. Protocols contain method metadata but no
223 /// implementations.
224 virtual void GenerateProtocol(const ObjCProtocolDecl *OPD) = 0;
225
226 /// GetOrEmitProtocol - Get the protocol object for the given
227 /// declaration, emitting it if necessary. The return value has type
228 /// ProtocolPtrTy.
229 virtual llvm::Constant *GetOrEmitProtocol(const ObjCProtocolDecl *PD) = 0;
230
231 /// Generate a function preamble for a method with the specified
232 /// types.
233
234 // FIXME: Current this just generates the Function definition, but really this
235 // should also be generating the loads of the parameters, as the runtime
236 // should have full control over how parameters are passed.
237 virtual llvm::Function *GenerateMethod(const ObjCMethodDecl *OMD,
238 const ObjCContainerDecl *CD) = 0;
239
240 /// Generates precondition checks for direct Objective-C Methods.
241 /// This includes [self self] for class methods and nil checks.
242 virtual void GenerateDirectMethodsPreconditionCheck(
243 CodeGenFunction &CGF, llvm::Function *Fn, const ObjCMethodDecl *OMD,
244 const ObjCContainerDecl *CD) = 0;
245
246 /// Generates prologue for direct Objective-C Methods.
247 virtual void GenerateDirectMethodPrologue(CodeGenFunction &CGF,
248 llvm::Function *Fn,
249 const ObjCMethodDecl *OMD,
250 const ObjCContainerDecl *CD) = 0;
251
252 /// Return the runtime function for getting properties.
253 virtual llvm::FunctionCallee GetPropertyGetFunction() = 0;
254
255 /// Return the runtime function for setting properties.
256 virtual llvm::FunctionCallee GetPropertySetFunction() = 0;
257
258 /// Return the runtime function for optimized setting properties.
259 virtual llvm::FunctionCallee GetOptimizedPropertySetFunction(bool atomic,
260 bool copy) = 0;
261
262 // API for atomic copying of qualified aggregates in getter.
263 virtual llvm::FunctionCallee GetGetStructFunction() = 0;
264 // API for atomic copying of qualified aggregates in setter.
265 virtual llvm::FunctionCallee GetSetStructFunction() = 0;
266 /// API for atomic copying of qualified aggregates with non-trivial copy
267 /// assignment (c++) in setter.
268 virtual llvm::FunctionCallee GetCppAtomicObjectSetFunction() = 0;
269 /// API for atomic copying of qualified aggregates with non-trivial copy
270 /// assignment (c++) in getter.
271 virtual llvm::FunctionCallee GetCppAtomicObjectGetFunction() = 0;
272
273 /// GetClass - Return a reference to the class for the given
274 /// interface decl.
275 virtual llvm::Value *GetClass(CodeGenFunction &CGF,
276 const ObjCInterfaceDecl *OID) = 0;
277
278 virtual llvm::Value *EmitNSAutoreleasePoolClassRef(CodeGenFunction &CGF) {
279 llvm_unreachable("autoreleasepool unsupported in this ABI");
280 }
281
282 /// EnumerationMutationFunction - Return the function that's called by the
283 /// compiler when a mutation is detected during foreach iteration.
284 virtual llvm::FunctionCallee EnumerationMutationFunction() = 0;
285
286 virtual void EmitSynchronizedStmt(CodeGen::CodeGenFunction &CGF,
287 const ObjCAtSynchronizedStmt &S) = 0;
288 virtual void EmitTryStmt(CodeGen::CodeGenFunction &CGF,
289 const ObjCAtTryStmt &S) = 0;
290 virtual void EmitThrowStmt(CodeGen::CodeGenFunction &CGF,
291 const ObjCAtThrowStmt &S,
292 bool ClearInsertionPoint = true) = 0;
293 virtual llvm::Value *EmitObjCWeakRead(CodeGen::CodeGenFunction &CGF,
294 Address AddrWeakObj) = 0;
295 virtual void EmitObjCWeakAssign(CodeGen::CodeGenFunction &CGF,
296 llvm::Value *src, Address dest) = 0;
297 virtual void EmitObjCGlobalAssign(CodeGen::CodeGenFunction &CGF,
298 llvm::Value *src, Address dest,
299 bool threadlocal = false) = 0;
300 virtual void EmitObjCIvarAssign(CodeGen::CodeGenFunction &CGF,
301 llvm::Value *src, Address dest,
302 llvm::Value *ivarOffset) = 0;
303 virtual void EmitObjCStrongCastAssign(CodeGen::CodeGenFunction &CGF,
304 llvm::Value *src, Address dest) = 0;
305
306 virtual LValue EmitObjCValueForIvar(CodeGen::CodeGenFunction &CGF,
307 QualType ObjectTy, llvm::Value *BaseValue,
308 const ObjCIvarDecl *Ivar,
309 unsigned CVRQualifiers) = 0;
310 virtual llvm::Value *EmitIvarOffset(CodeGen::CodeGenFunction &CGF,
311 const ObjCInterfaceDecl *Interface,
312 const ObjCIvarDecl *Ivar) = 0;
313 virtual void EmitGCMemmoveCollectable(CodeGen::CodeGenFunction &CGF,
314 Address DestPtr, Address SrcPtr,
315 llvm::Value *Size) = 0;
316 virtual llvm::Constant *
317 BuildGCBlockLayout(CodeGen::CodeGenModule &CGM,
318 const CodeGen::CGBlockInfo &blockInfo) = 0;
319 virtual llvm::Constant *
320 BuildRCBlockLayout(CodeGen::CodeGenModule &CGM,
321 const CodeGen::CGBlockInfo &blockInfo) = 0;
322 virtual std::string getRCBlockLayoutStr(CodeGen::CodeGenModule &CGM,
323 const CGBlockInfo &blockInfo) {
324 return {};
325 }
326
327 /// Returns an i8* which points to the byref layout information.
328 virtual llvm::Constant *BuildByrefLayout(CodeGen::CodeGenModule &CGM,
329 QualType T) = 0;
330
331 struct MessageSendInfo {
332 const CGFunctionInfo &CallInfo;
333 llvm::PointerType *MessengerType;
334
335 MessageSendInfo(const CGFunctionInfo &callInfo,
336 llvm::PointerType *messengerType)
337 : CallInfo(callInfo), MessengerType(messengerType) {}
338 };
339
340 MessageSendInfo getMessageSendInfo(const ObjCMethodDecl *method,
341 QualType resultType,
342 CallArgList &callArgs);
343
344 bool canMessageReceiverBeNull(CodeGenFunction &CGF,
345 const ObjCMethodDecl *method, bool isSuper,
346 const ObjCInterfaceDecl *classReceiver,
347 llvm::Value *receiver);
348
349 /// Check if a class object can be unrealized (not yet initialized).
350 /// Returns true if the class may be unrealized, false if provably realized.
351 ///
352 /// TODO: Returns false if:
353 /// - An instance method on the same class was called in a dominating path
354 /// - The class was explicitly realized earlier in control flow
355 /// - Note: [Parent foo] does NOT realize Child (inheritance care needed)
356 bool canClassObjectBeUnrealized(const ObjCInterfaceDecl *ClassDecl,
357 CodeGenFunction &CGF) const;
358
359 static bool isWeakLinkedClass(const ObjCInterfaceDecl *cls);
360
361 /// Destroy the callee-destroyed arguments of the given method,
362 /// if it has any. Used for nil-receiver paths in message sends.
363 /// Never does anything if the method does not satisfy
364 /// hasParamDestroyedInCallee().
365 ///
366 /// \param callArgs - just the formal arguments, not including implicit
367 /// arguments such as self and cmd
368 static void destroyCalleeDestroyedArguments(CodeGenFunction &CGF,
369 const ObjCMethodDecl *method,
370 const CallArgList &callArgs);
371
372 // FIXME: This probably shouldn't be here, but the code to compute
373 // it is here.
374 unsigned ComputeBitfieldBitOffset(CodeGen::CodeGenModule &CGM,
375 const ObjCInterfaceDecl *ID,
376 const ObjCIvarDecl *Ivar);
377};
378
379/// Creates an instance of an Objective-C runtime class.
380// TODO: This should include some way of selecting which runtime to target.
381CGObjCRuntime *CreateGNUObjCRuntime(CodeGenModule &CGM);
382CGObjCRuntime *CreateMacObjCRuntime(CodeGenModule &CGM);
383} // namespace CodeGen
384} // namespace clang
385#endif
386