Coverage Report

Created: 2024-01-17 10:31

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