Coverage Report

Created: 2022-05-21 09:15

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