Coverage Report

Created: 2020-11-24 06:42

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