Coverage Report

Created: 2020-09-15 12:33

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