Coverage Report

Created: 2021-06-15 06:44

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