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
24namespace llvm {
25  class Constant;
26  class Function;
27  class Module;
28  class StructLayout;
29  class StructType;
30  class Type;
31  class Value;
32}
33
34namespace clang {
35namespace CodeGen {
36  class CodeGenFunction;
37}
38
39  class FieldDecl;
40  class ObjCAtTryStmt;
41  class ObjCAtThrowStmt;
42  class ObjCAtSynchronizedStmt;
43  class ObjCContainerDecl;
44  class ObjCCategoryImplDecl;
45  class ObjCImplementationDecl;
46  class ObjCInterfaceDecl;
47  class ObjCMessageExpr;
48  class ObjCMethodDecl;
49  class ObjCProtocolDecl;
50  class Selector;
51  class ObjCIvarDecl;
52  class ObjCStringLiteral;
53  class BlockDeclRefExpr;
54
55namespace CodeGen {
56  class CodeGenModule;
57  class CGBlockInfo;
58
59// FIXME: Several methods should be pure virtual but aren't to avoid the
60// partially-implemented subclass breaking.
61
62/// Implements runtime-specific code generation functions.
63class CGObjCRuntime {
64protected:
65  CodeGen::CodeGenModule &CGM;
66  CGObjCRuntime(CodeGen::CodeGenModule &CGM) : CGM(CGM) {}
67
68  // Utility functions for unified ivar access. These need to
69  // eventually be folded into other places (the structure layout
70  // code).
71
72  /// Compute an offset to the given ivar, suitable for passing to
73  /// EmitValueForIvarAtOffset.  Note that the correct handling of
74  /// bit-fields is carefully coordinated by these two, use caution!
75  ///
76  /// The latter overload is suitable for computing the offset of a
77  /// sythesized ivar.
78  uint64_t ComputeIvarBaseOffset(CodeGen::CodeGenModule &CGM,
79                                 const ObjCInterfaceDecl *OID,
80                                 const ObjCIvarDecl *Ivar);
81  uint64_t ComputeIvarBaseOffset(CodeGen::CodeGenModule &CGM,
82                                 const ObjCImplementationDecl *OID,
83                                 const ObjCIvarDecl *Ivar);
84
85  LValue EmitValueForIvarAtOffset(CodeGen::CodeGenFunction &CGF,
86                                  const ObjCInterfaceDecl *OID,
87                                  llvm::Value *BaseValue,
88                                  const ObjCIvarDecl *Ivar,
89                                  unsigned CVRQualifiers,
90                                  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  /// Generate the function required to register all Objective-C components in
119  /// this compilation unit with the runtime library.
120  virtual llvm::Function *ModuleInitFunction() = 0;
121
122  /// Get a selector for the specified name and type values.
123  /// The result should have the LLVM type for ASTContext::getObjCSelType().
124  virtual llvm::Value *GetSelector(CodeGenFunction &CGF, Selector Sel) = 0;
125
126  /// Get the address of a selector for the specified name and type values.
127  /// This is a rarely-used language extension, but sadly it exists.
128  ///
129  /// The result should have the LLVM type for a pointer to
130  /// ASTContext::getObjCSelType().
131  virtual Address GetAddrOfSelector(CodeGenFunction &CGF, Selector Sel) = 0;
132
133  /// Get a typed selector.
134  virtual llvm::Value *GetSelector(CodeGenFunction &CGF,
135                                   const ObjCMethodDecl *Method) = 0;
136
137  /// Get the type constant to catch for the given ObjC pointer type.
138  /// This is used externally to implement catching ObjC types in C++.
139  /// Runtimes which don't support this should add the appropriate
140  /// error to Sema.
141  virtual llvm::Constant *GetEHType(QualType T) = 0;
142
143  virtual CatchTypeInfo getCatchAllTypeInfo() { return { nullptr, 0 }; }
144
145  /// Generate a constant string object.
146  virtual ConstantAddress GenerateConstantString(const StringLiteral *) = 0;
147
148  /// Generate a category.  A category contains a list of methods (and
149  /// accompanying metadata) and a list of protocols.
150  virtual void GenerateCategory(const ObjCCategoryImplDecl *OCD) = 0;
151
152  /// Generate a class structure for this class.
153  virtual void GenerateClass(const ObjCImplementationDecl *OID) = 0;
154
155  /// Register an class alias.
156  virtual void RegisterAlias(const ObjCCompatibleAliasDecl *OAD) = 0;
157
158  /// Generate an Objective-C message send operation.
159  ///
160  /// \param Method - The method being called, this may be null if synthesizing
161  /// a property setter or getter.
162  virtual CodeGen::RValue
163  GenerateMessageSend(CodeGen::CodeGenFunction &CGF,
164                      ReturnValueSlot ReturnSlot,
165                      QualType ResultType,
166                      Selector Sel,
167                      llvm::Value *Receiver,
168                      const CallArgList &CallArgs,
169                      const ObjCInterfaceDecl *Class = nullptr,
170                      const ObjCMethodDecl *Method = nullptr) = 0;
171
172  /// Generate an Objective-C message send operation.
173  ///
174  /// This variant allows for the call to be substituted with an optimized
175  /// variant.
176  CodeGen::RValue
177  GeneratePossiblySpecializedMessageSend(CodeGenFunction &CGF,
178                                         ReturnValueSlot Return,
179                                         QualType ResultType,
180                                         Selector Sel,
181                                         llvm::Value *Receiver,
182                                         const CallArgList& Args,
183                                         const ObjCInterfaceDecl *OID,
184                                         const ObjCMethodDecl *Method,
185                                         bool isClassMessage);
186
187  /// Generate an Objective-C message send operation to the super
188  /// class initiated in a method for Class and with the given Self
189  /// object.
190  ///
191  /// \param Method - The method being called, this may be null if synthesizing
192  /// a property setter or getter.
193  virtual CodeGen::RValue
194  GenerateMessageSendSuper(CodeGen::CodeGenFunction &CGF,
195                           ReturnValueSlot ReturnSlot,
196                           QualType ResultType,
197                           Selector Sel,
198                           const ObjCInterfaceDecl *Class,
199                           bool isCategoryImpl,
200                           llvm::Value *Self,
201                           bool IsClassMessage,
202                           const CallArgList &CallArgs,
203                           const ObjCMethodDecl *Method = nullptr) = 0;
204
205  /// Emit the code to return the named protocol as an object, as in a
206  /// \@protocol expression.
207  virtual llvm::Value *GenerateProtocolRef(CodeGenFunction &CGF,
208                                           const ObjCProtocolDecl *OPD) = 0;
209
210  /// Generate the named protocol.  Protocols contain method metadata but no
211  /// implementations.
212  virtual void GenerateProtocol(const ObjCProtocolDecl *OPD) = 0;
213
214  /// Generate a function preamble for a method with the specified
215  /// types.
216
217  // FIXME: Current this just generates the Function definition, but really this
218  // should also be generating the loads of the parameters, as the runtime
219  // should have full control over how parameters are passed.
220  virtual llvm::Function *GenerateMethod(const ObjCMethodDecl *OMD,
221                                         const ObjCContainerDecl *CD) = 0;
222
223  /// Generates prologue for direct Objective-C Methods.
224  virtual void GenerateDirectMethodPrologue(CodeGenFunction &CGF,
225                                            llvm::Function *Fn,
226                                            const ObjCMethodDecl *OMD,
227                                            const ObjCContainerDecl *CD) = 0;
228
229  /// Return the runtime function for getting properties.
230  virtual llvm::FunctionCallee GetPropertyGetFunction() = 0;
231
232  /// Return the runtime function for setting properties.
233  virtual llvm::FunctionCallee GetPropertySetFunction() = 0;
234
235  /// Return the runtime function for optimized setting properties.
236  virtual llvm::FunctionCallee GetOptimizedPropertySetFunction(bool atomic,
237                                                               bool copy) = 0;
238
239  // API for atomic copying of qualified aggregates in getter.
240  virtual llvm::FunctionCallee GetGetStructFunction() = 0;
241  // API for atomic copying of qualified aggregates in setter.
242  virtual llvm::FunctionCallee GetSetStructFunction() = 0;
243  /// API for atomic copying of qualified aggregates with non-trivial copy
244  /// assignment (c++) in setter.
245  virtual llvm::FunctionCallee GetCppAtomicObjectSetFunction() = 0;
246  /// API for atomic copying of qualified aggregates with non-trivial copy
247  /// assignment (c++) in getter.
248  virtual llvm::FunctionCallee GetCppAtomicObjectGetFunction() = 0;
249
250  /// GetClass - Return a reference to the class for the given
251  /// interface decl.
252  virtual llvm::Value *GetClass(CodeGenFunction &CGF,
253                                const ObjCInterfaceDecl *OID) = 0;
254
255
256  virtual llvm::Value *EmitNSAutoreleasePoolClassRef(CodeGenFunction &CGF) {
257    llvm_unreachable("autoreleasepool unsupported in this ABI");
258  }
259
260  /// EnumerationMutationFunction - Return the function that's called by the
261  /// compiler when a mutation is detected during foreach iteration.
262  virtual llvm::FunctionCallee EnumerationMutationFunction() = 0;
263
264  virtual void EmitSynchronizedStmt(CodeGen::CodeGenFunction &CGF,
265                                    const ObjCAtSynchronizedStmt &S) = 0;
266  virtual void EmitTryStmt(CodeGen::CodeGenFunction &CGF,
267                           const ObjCAtTryStmt &S) = 0;
268  virtual void EmitThrowStmt(CodeGen::CodeGenFunction &CGF,
269                             const ObjCAtThrowStmt &S,
270                             bool ClearInsertionPoint=true) = 0;
271  virtual llvm::Value *EmitObjCWeakRead(CodeGen::CodeGenFunction &CGF,
272                                        Address AddrWeakObj) = 0;
273  virtual void EmitObjCWeakAssign(CodeGen::CodeGenFunction &CGF,
274                                  llvm::Value *src, Address dest) = 0;
275  virtual void EmitObjCGlobalAssign(CodeGen::CodeGenFunction &CGF,
276                                    llvm::Value *src, Address dest,
277                                    bool threadlocal=false) = 0;
278  virtual void EmitObjCIvarAssign(CodeGen::CodeGenFunction &CGF,
279                                  llvm::Value *src, Address dest,
280                                  llvm::Value *ivarOffset) = 0;
281  virtual void EmitObjCStrongCastAssign(CodeGen::CodeGenFunction &CGF,
282                                        llvm::Value *src, Address dest) = 0;
283
284  virtual LValue EmitObjCValueForIvar(CodeGen::CodeGenFunction &CGF,
285                                      QualType ObjectTy,
286                                      llvm::Value *BaseValue,
287                                      const ObjCIvarDecl *Ivar,
288                                      unsigned CVRQualifiers) = 0;
289  virtual llvm::Value *EmitIvarOffset(CodeGen::CodeGenFunction &CGF,
290                                      const ObjCInterfaceDecl *Interface,
291                                      const ObjCIvarDecl *Ivar) = 0;
292  virtual void EmitGCMemmoveCollectable(CodeGen::CodeGenFunction &CGF,
293                                        Address DestPtr,
294                                        Address SrcPtr,
295                                        llvm::Value *Size) = 0;
296  virtual llvm::Constant *BuildGCBlockLayout(CodeGen::CodeGenModule &CGM,
297                                  const CodeGen::CGBlockInfo &blockInfo) = 0;
298  virtual llvm::Constant *BuildRCBlockLayout(CodeGen::CodeGenModule &CGM,
299                                  const CodeGen::CGBlockInfo &blockInfo) = 0;
300  virtual std::string getRCBlockLayoutStr(CodeGen::CodeGenModule &CGM,
301                                          const CGBlockInfo &blockInfo) {
302    return {};
303  }
304
305  /// Returns an i8* which points to the byref layout information.
306  virtual llvm::Constant *BuildByrefLayout(CodeGen::CodeGenModule &CGM,
307                                           QualType T) = 0;
308
309  struct MessageSendInfo {
310    const CGFunctionInfo &CallInfo;
311    llvm::PointerType *MessengerType;
312
313    MessageSendInfo(const CGFunctionInfo &callInfo,
314                    llvm::PointerType *messengerType)
315      : CallInfo(callInfo), MessengerType(messengerType) {}
316  };
317
318  MessageSendInfo getMessageSendInfo(const ObjCMethodDecl *method,
319                                     QualType resultType,
320                                     CallArgList &callArgs);
321
322  // FIXME: This probably shouldn't be here, but the code to compute
323  // it is here.
324  unsigned ComputeBitfieldBitOffset(CodeGen::CodeGenModule &CGM,
325                                    const ObjCInterfaceDecl *ID,
326                                    const ObjCIvarDecl *Ivar);
327};
328
329/// Creates an instance of an Objective-C runtime class.
330//TODO: This should include some way of selecting which runtime to target.
331CGObjCRuntime *CreateGNUObjCRuntime(CodeGenModule &CGM);
332CGObjCRuntime *CreateMacObjCRuntime(CodeGenModule &CGM);
333}
334}
335#endif
336