Coverage Report

Created: 2022-01-25 06:29

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