Coverage Report

Created: 2017-10-03 07:32

/Users/buildslave/jenkins/sharedspace/clang-stage2-coverage-R@2/llvm/tools/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
//                     The LLVM Compiler Infrastructure
4
//
5
// This file is distributed under the University of Illinois Open Source
6
// License. See LICENSE.TXT for details.
7
//
8
//===----------------------------------------------------------------------===//
9
//
10
// This provides Objective-C code generation targeting the GNU runtime.  The
11
// class in this file generates structures used by the GNU Objective-C runtime
12
// library.  These structures are defined in objc/objc.h and objc/objc-api.h in
13
// the GNU runtime distribution.
14
//
15
//===----------------------------------------------------------------------===//
16
17
#include "CGObjCRuntime.h"
18
#include "CGCleanup.h"
19
#include "CodeGenFunction.h"
20
#include "CodeGenModule.h"
21
#include "clang/CodeGen/ConstantInitBuilder.h"
22
#include "clang/AST/ASTContext.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 "llvm/ADT/SmallVector.h"
30
#include "llvm/ADT/StringMap.h"
31
#include "llvm/IR/CallSite.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
38
using namespace clang;
39
using namespace CodeGen;
40
41
namespace {
42
/// Class that lazily initialises the runtime function.  Avoids inserting the
43
/// types and the function declaration into a module if they're not used, and
44
/// avoids constructing the type more than once if it's used more than once.
45
class LazyRuntimeFunction {
46
  CodeGenModule *CGM;
47
  llvm::FunctionType *FTy;
48
  const char *FunctionName;
49
  llvm::Constant *Function;
50
51
public:
52
  /// Constructor leaves this class uninitialized, because it is intended to
53
  /// be used as a field in another class and not all of the types that are
54
  /// used as arguments will necessarily be available at construction time.
55
  LazyRuntimeFunction()
56
489
      : CGM(nullptr), FunctionName(nullptr), Function(nullptr) {}
57
58
  /// Initialises the lazy function with the name, return type, and the types
59
  /// of the arguments.
60
  template <typename... Tys>
61
  void init(CodeGenModule *Mod, const char *name, llvm::Type *RetTy,
62
317
            Tys *... Types) {
63
317
    CGM = Mod;
64
317
    FunctionName = name;
65
317
    Function = nullptr;
66
317
    if(
sizeof...(Tys)317
) {
67
313
      SmallVector<llvm::Type *, 8> ArgTys({Types...});
68
313
      FTy = llvm::FunctionType::get(RetTy, ArgTys, false);
69
313
    }
70
4
    else {
71
4
      FTy = llvm::FunctionType::get(RetTy, None, false);
72
4
    }
73
317
  }
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
62
23
            Tys *... Types) {
63
23
    CGM = Mod;
64
23
    FunctionName = name;
65
23
    Function = nullptr;
66
23
    if(
sizeof...(Tys)23
) {
67
23
      SmallVector<llvm::Type *, 8> ArgTys({Types...});
68
23
      FTy = llvm::FunctionType::get(RetTy, ArgTys, false);
69
23
    }
70
0
    else {
71
0
      FTy = llvm::FunctionType::get(RetTy, None, false);
72
0
    }
73
23
  }
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
62
23
            Tys *... Types) {
63
23
    CGM = Mod;
64
23
    FunctionName = name;
65
23
    Function = nullptr;
66
23
    if(
sizeof...(Tys)23
) {
67
23
      SmallVector<llvm::Type *, 8> ArgTys({Types...});
68
23
      FTy = llvm::FunctionType::get(RetTy, ArgTys, false);
69
23
    }
70
0
    else {
71
0
      FTy = llvm::FunctionType::get(RetTy, None, false);
72
0
    }
73
23
  }
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
62
46
            Tys *... Types) {
63
46
    CGM = Mod;
64
46
    FunctionName = name;
65
46
    Function = nullptr;
66
46
    if(
sizeof...(Tys)46
) {
67
46
      SmallVector<llvm::Type *, 8> ArgTys({Types...});
68
46
      FTy = llvm::FunctionType::get(RetTy, ArgTys, false);
69
46
    }
70
0
    else {
71
0
      FTy = llvm::FunctionType::get(RetTy, None, false);
72
0
    }
73
46
  }
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
62
21
            Tys *... Types) {
63
21
    CGM = Mod;
64
21
    FunctionName = name;
65
21
    Function = nullptr;
66
21
    if(
sizeof...(Tys)21
) {
67
21
      SmallVector<llvm::Type *, 8> ArgTys({Types...});
68
21
      FTy = llvm::FunctionType::get(RetTy, ArgTys, false);
69
21
    }
70
0
    else {
71
0
      FTy = llvm::FunctionType::get(RetTy, None, false);
72
0
    }
73
21
  }
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
62
49
            Tys *... Types) {
63
49
    CGM = Mod;
64
49
    FunctionName = name;
65
49
    Function = nullptr;
66
49
    if(
sizeof...(Tys)49
) {
67
49
      SmallVector<llvm::Type *, 8> ArgTys({Types...});
68
49
      FTy = llvm::FunctionType::get(RetTy, ArgTys, false);
69
49
    }
70
0
    else {
71
0
      FTy = llvm::FunctionType::get(RetTy, None, false);
72
0
    }
73
49
  }
CGObjCGNU.cpp:void (anonymous namespace)::LazyRuntimeFunction::init<llvm::PointerType>(clang::CodeGen::CodeGenModule*, char const*, llvm::Type*, llvm::PointerType*)
Line
Count
Source
62
123
            Tys *... Types) {
63
123
    CGM = Mod;
64
123
    FunctionName = name;
65
123
    Function = nullptr;
66
123
    if(
sizeof...(Tys)123
) {
67
123
      SmallVector<llvm::Type *, 8> ArgTys({Types...});
68
123
      FTy = llvm::FunctionType::get(RetTy, ArgTys, false);
69
123
    }
70
0
    else {
71
0
      FTy = llvm::FunctionType::get(RetTy, None, false);
72
0
    }
73
123
  }
CGObjCGNU.cpp:void (anonymous namespace)::LazyRuntimeFunction::init<>(clang::CodeGen::CodeGenModule*, char const*, llvm::Type*)
Line
Count
Source
62
4
            Tys *... Types) {
63
4
    CGM = Mod;
64
4
    FunctionName = name;
65
4
    Function = nullptr;
66
4
    if(
sizeof...(Tys)4
) {
67
0
      SmallVector<llvm::Type *, 8> ArgTys({Types...});
68
0
      FTy = llvm::FunctionType::get(RetTy, ArgTys, false);
69
0
    }
70
4
    else {
71
4
      FTy = llvm::FunctionType::get(RetTy, None, false);
72
4
    }
73
4
  }
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
62
28
            Tys *... Types) {
63
28
    CGM = Mod;
64
28
    FunctionName = name;
65
28
    Function = nullptr;
66
28
    if(
sizeof...(Tys)28
) {
67
28
      SmallVector<llvm::Type *, 8> ArgTys({Types...});
68
28
      FTy = llvm::FunctionType::get(RetTy, ArgTys, false);
69
28
    }
70
0
    else {
71
0
      FTy = llvm::FunctionType::get(RetTy, None, false);
72
0
    }
73
28
  }
74
75
0
  llvm::FunctionType *getType() { return FTy; }
76
77
  /// Overloaded cast operator, allows the class to be implicitly cast to an
78
  /// LLVM constant.
79
49
  operator llvm::Constant *() {
80
49
    if (
!Function49
) {
81
33
      if (!FunctionName)
82
6
        return nullptr;
83
27
      Function =
84
27
          cast<llvm::Constant>(CGM->CreateRuntimeFunction(FTy, FunctionName));
85
27
    }
86
43
    return Function;
87
49
  }
88
7
  operator llvm::Function *() {
89
7
    return cast<llvm::Function>((llvm::Constant *)*this);
90
7
  }
91
};
92
93
94
/// GNU Objective-C runtime code generation.  This class implements the parts of
95
/// Objective-C support that are specific to the GNU family of runtimes (GCC,
96
/// GNUstep and ObjFW).
97
class CGObjCGNU : public CGObjCRuntime {
98
protected:
99
  /// The LLVM module into which output is inserted
100
  llvm::Module &TheModule;
101
  /// strut objc_super.  Used for sending messages to super.  This structure
102
  /// contains the receiver (object) and the expected class.
103
  llvm::StructType *ObjCSuperTy;
104
  /// struct objc_super*.  The type of the argument to the superclass message
105
  /// lookup functions.  
106
  llvm::PointerType *PtrToObjCSuperTy;
107
  /// LLVM type for selectors.  Opaque pointer (i8*) unless a header declaring
108
  /// SEL is included in a header somewhere, in which case it will be whatever
109
  /// type is declared in that header, most likely {i8*, i8*}.
110
  llvm::PointerType *SelectorTy;
111
  /// LLVM i8 type.  Cached here to avoid repeatedly getting it in all of the
112
  /// places where it's used
113
  llvm::IntegerType *Int8Ty;
114
  /// Pointer to i8 - LLVM type of char*, for all of the places where the
115
  /// runtime needs to deal with C strings.
116
  llvm::PointerType *PtrToInt8Ty;
117
  /// Instance Method Pointer type.  This is a pointer to a function that takes,
118
  /// at a minimum, an object and a selector, and is the generic type for
119
  /// Objective-C methods.  Due to differences between variadic / non-variadic
120
  /// calling conventions, it must always be cast to the correct type before
121
  /// actually being used.
122
  llvm::PointerType *IMPTy;
123
  /// Type of an untyped Objective-C object.  Clang treats id as a built-in type
124
  /// when compiling Objective-C code, so this may be an opaque pointer (i8*),
125
  /// but if the runtime header declaring it is included then it may be a
126
  /// pointer to a structure.
127
  llvm::PointerType *IdTy;
128
  /// Pointer to a pointer to an Objective-C object.  Used in the new ABI
129
  /// message lookup function and some GC-related functions.
130
  llvm::PointerType *PtrToIdTy;
131
  /// The clang type of id.  Used when using the clang CGCall infrastructure to
132
  /// call Objective-C methods.
133
  CanQualType ASTIdTy;
134
  /// LLVM type for C int type.
135
  llvm::IntegerType *IntTy;
136
  /// LLVM type for an opaque pointer.  This is identical to PtrToInt8Ty, but is
137
  /// used in the code to document the difference between i8* meaning a pointer
138
  /// to a C string and i8* meaning a pointer to some opaque type.
139
  llvm::PointerType *PtrTy;
140
  /// LLVM type for C long type.  The runtime uses this in a lot of places where
141
  /// it should be using intptr_t, but we can't fix this without breaking
142
  /// compatibility with GCC...
143
  llvm::IntegerType *LongTy;
144
  /// LLVM type for C size_t.  Used in various runtime data structures.
145
  llvm::IntegerType *SizeTy;
146
  /// LLVM type for C intptr_t.  
147
  llvm::IntegerType *IntPtrTy;
148
  /// LLVM type for C ptrdiff_t.  Mainly used in property accessor functions.
149
  llvm::IntegerType *PtrDiffTy;
150
  /// LLVM type for C int*.  Used for GCC-ABI-compatible non-fragile instance
151
  /// variables.
152
  llvm::PointerType *PtrToIntTy;
153
  /// LLVM type for Objective-C BOOL type.
154
  llvm::Type *BoolTy;
155
  /// 32-bit integer type, to save us needing to look it up every time it's used.
156
  llvm::IntegerType *Int32Ty;
157
  /// 64-bit integer type, to save us needing to look it up every time it's used.
158
  llvm::IntegerType *Int64Ty;
159
  /// Metadata kind used to tie method lookups to message sends.  The GNUstep
160
  /// runtime provides some LLVM passes that can use this to do things like
161
  /// automatic IMP caching and speculative inlining.
162
  unsigned msgSendMDKind;
163
164
  /// Helper function that generates a constant string and returns a pointer to
165
  /// the start of the string.  The result of this function can be used anywhere
166
  /// where the C code specifies const char*.  
167
272
  llvm::Constant *MakeConstantString(StringRef Str, const char *Name = "") {
168
272
    ConstantAddress Array = CGM.GetAddrOfConstantCString(Str, Name);
169
272
    return llvm::ConstantExpr::getGetElementPtr(Array.getElementType(),
170
272
                                                Array.getPointer(), Zeros);
171
272
  }
172
173
  /// Emits a linkonce_odr string, whose name is the prefix followed by the
174
  /// string value.  This allows the linker to combine the strings between
175
  /// different modules.  Used for EH typeinfo names, selector strings, and a
176
  /// few other things.
177
19
  llvm::Constant *ExportUniqueString(const std::string &Str, StringRef Prefix) {
178
19
    std::string Name = Prefix.str() + Str;
179
19
    auto *ConstStr = TheModule.getGlobalVariable(Name);
180
19
    if (
!ConstStr19
) {
181
19
      llvm::Constant *value = llvm::ConstantDataArray::getString(VMContext,Str);
182
19
      ConstStr = new llvm::GlobalVariable(TheModule, value->getType(), true,
183
19
                                          llvm::GlobalValue::LinkOnceODRLinkage,
184
19
                                          value, Name);
185
19
    }
186
19
    return llvm::ConstantExpr::getGetElementPtr(ConstStr->getValueType(),
187
19
                                                ConstStr, Zeros);
188
19
  }
189
190
  /// Generates a global structure, initialized by the elements in the vector.
191
  /// The element types must match the types of the structure elements in the
192
  /// first argument.
193
  llvm::GlobalVariable *MakeGlobal(llvm::Constant *C,
194
                                   CharUnits Align,
195
                                   StringRef Name="",
196
                                   llvm::GlobalValue::LinkageTypes linkage
197
0
                                         =llvm::GlobalValue::InternalLinkage) {
198
0
    auto GV = new llvm::GlobalVariable(TheModule, C->getType(), false,
199
0
                                       linkage, C, Name);
200
0
    GV->setAlignment(Align.getQuantity());
201
0
    return GV;
202
0
  }
203
204
  /// Returns a property name and encoding string.
205
  llvm::Constant *MakePropertyEncodingString(const ObjCPropertyDecl *PD,
206
12
                                             const Decl *Container) {
207
12
    const ObjCRuntime &R = CGM.getLangOpts().ObjCRuntime;
208
12
    if ((R.getKind() == ObjCRuntime::GNUstep) &&
209
12
        
(R.getVersion() >= VersionTuple(1, 6))8
) {
210
7
      std::string NameAndAttributes;
211
7
      std::string TypeStr =
212
7
        CGM.getContext().getObjCEncodingForPropertyDecl(PD, Container);
213
7
      NameAndAttributes += '\0';
214
7
      NameAndAttributes += TypeStr.length() + 3;
215
7
      NameAndAttributes += TypeStr;
216
7
      NameAndAttributes += '\0';
217
7
      NameAndAttributes += PD->getNameAsString();
218
7
      return MakeConstantString(NameAndAttributes);
219
7
    }
220
5
    return MakeConstantString(PD->getNameAsString());
221
5
  }
222
223
  /// Push the property attributes into two structure fields. 
224
  void PushPropertyAttributes(ConstantStructBuilder &Fields,
225
      ObjCPropertyDecl *property, bool isSynthesized=true, bool
226
12
      isDynamic=true) {
227
12
    int attrs = property->getPropertyAttributes();
228
12
    // For read-only properties, clear the copy and retain flags
229
12
    if (
attrs & ObjCPropertyDecl::OBJC_PR_readonly12
) {
230
1
      attrs &= ~ObjCPropertyDecl::OBJC_PR_copy;
231
1
      attrs &= ~ObjCPropertyDecl::OBJC_PR_retain;
232
1
      attrs &= ~ObjCPropertyDecl::OBJC_PR_weak;
233
1
      attrs &= ~ObjCPropertyDecl::OBJC_PR_strong;
234
1
    }
235
12
    // The first flags field has the same attribute values as clang uses internally
236
12
    Fields.addInt(Int8Ty, attrs & 0xff);
237
12
    attrs >>= 8;
238
12
    attrs <<= 2;
239
12
    // For protocol properties, synthesized and dynamic have no meaning, so we
240
12
    // reuse these flags to indicate that this is a protocol property (both set
241
12
    // has no meaning, as a property can't be both synthesized and dynamic)
242
12
    attrs |= isSynthesized ? 
(1<<0)11
:
01
;
243
12
    attrs |= isDynamic ? 
(1<<1)1
:
011
;
244
12
    // The second field is the next four fields left shifted by two, with the
245
12
    // low bit set to indicate whether the field is synthesized or dynamic.
246
12
    Fields.addInt(Int8Ty, attrs & 0xff);
247
12
    // Two padding fields
248
12
    Fields.addInt(Int8Ty, 0);
249
12
    Fields.addInt(Int8Ty, 0);
250
12
  }
251
252
  /// Ensures that the value has the required type, by inserting a bitcast if
253
  /// required.  This function lets us avoid inserting bitcasts that are
254
  /// redundant.
255
96
  llvm::Value* EnforceType(CGBuilderTy &B, llvm::Value *V, llvm::Type *Ty) {
256
96
    if (
V->getType() == Ty96
)
return V71
;
257
25
    return B.CreateBitCast(V, Ty);
258
25
  }
259
6
  Address EnforceType(CGBuilderTy &B, Address V, llvm::Type *Ty) {
260
6
    if (
V.getType() == Ty6
)
return V4
;
261
2
    return B.CreateBitCast(V, Ty);
262
2
  }
263
264
  // Some zeros used for GEPs in lots of places.
265
  llvm::Constant *Zeros[2];
266
  /// Null pointer value.  Mainly used as a terminator in various arrays.
267
  llvm::Constant *NULLPtr;
268
  /// LLVM context.
269
  llvm::LLVMContext &VMContext;
270
271
private:
272
  /// Placeholder for the class.  Lots of things refer to the class before we've
273
  /// actually emitted it.  We use this alias as a placeholder, and then replace
274
  /// it with a pointer to the class structure before finally emitting the
275
  /// module.
276
  llvm::GlobalAlias *ClassPtrAlias;
277
  /// Placeholder for the metaclass.  Lots of things refer to the class before
278
  /// we've / actually emitted it.  We use this alias as a placeholder, and then
279
  /// replace / it with a pointer to the metaclass structure before finally
280
  /// emitting the / module.
281
  llvm::GlobalAlias *MetaClassPtrAlias;
282
  /// All of the classes that have been generated for this compilation units.
283
  std::vector<llvm::Constant*> Classes;
284
  /// All of the categories that have been generated for this compilation units.
285
  std::vector<llvm::Constant*> Categories;
286
  /// All of the Objective-C constant strings that have been generated for this
287
  /// compilation units.
288
  std::vector<llvm::Constant*> ConstantStrings;
289
  /// Map from string values to Objective-C constant strings in the output.
290
  /// Used to prevent emitting Objective-C strings more than once.  This should
291
  /// not be required at all - CodeGenModule should manage this list.
292
  llvm::StringMap<llvm::Constant*> ObjCStrings;
293
  /// All of the protocols that have been declared.
294
  llvm::StringMap<llvm::Constant*> ExistingProtocols;
295
  /// For each variant of a selector, we store the type encoding and a
296
  /// placeholder value.  For an untyped selector, the type will be the empty
297
  /// string.  Selector references are all done via the module's selector table,
298
  /// so we create an alias as a placeholder and then replace it with the real
299
  /// value later.
300
  typedef std::pair<std::string, llvm::GlobalAlias*> TypedSelector;
301
  /// Type of the selector map.  This is roughly equivalent to the structure
302
  /// used in the GNUstep runtime, which maintains a list of all of the valid
303
  /// types for a selector in a table.
304
  typedef llvm::DenseMap<Selector, SmallVector<TypedSelector, 2> >
305
    SelectorMap;
306
  /// A map from selectors to selector types.  This allows us to emit all
307
  /// selectors of the same name and type together.
308
  SelectorMap SelectorTable;
309
310
  /// Selectors related to memory management.  When compiling in GC mode, we
311
  /// omit these.
312
  Selector RetainSel, ReleaseSel, AutoreleaseSel;
313
  /// Runtime functions used for memory management in GC mode.  Note that clang
314
  /// supports code generation for calling these functions, but neither GNU
315
  /// runtime actually supports this API properly yet.
316
  LazyRuntimeFunction IvarAssignFn, StrongCastAssignFn, MemMoveFn, WeakReadFn, 
317
    WeakAssignFn, GlobalAssignFn;
318
319
  typedef std::pair<std::string, std::string> ClassAliasPair;
320
  /// All classes that have aliases set for them.
321
  std::vector<ClassAliasPair> ClassAliases;
322
323
protected:
324
  /// Function used for throwing Objective-C exceptions.
325
  LazyRuntimeFunction ExceptionThrowFn;
326
  /// Function used for rethrowing exceptions, used at the end of \@finally or
327
  /// \@synchronize blocks.
328
  LazyRuntimeFunction ExceptionReThrowFn;
329
  /// Function called when entering a catch function.  This is required for
330
  /// differentiating Objective-C exceptions and foreign exceptions.
331
  LazyRuntimeFunction EnterCatchFn;
332
  /// Function called when exiting from a catch block.  Used to do exception
333
  /// cleanup.
334
  LazyRuntimeFunction ExitCatchFn;
335
  /// Function called when entering an \@synchronize block.  Acquires the lock.
336
  LazyRuntimeFunction SyncEnterFn;
337
  /// Function called when exiting an \@synchronize block.  Releases the lock.
338
  LazyRuntimeFunction SyncExitFn;
339
340
private:
341
  /// Function called if fast enumeration detects that the collection is
342
  /// modified during the update.
343
  LazyRuntimeFunction EnumerationMutationFn;
344
  /// Function for implementing synthesized property getters that return an
345
  /// object.
346
  LazyRuntimeFunction GetPropertyFn;
347
  /// Function for implementing synthesized property setters that return an
348
  /// object.
349
  LazyRuntimeFunction SetPropertyFn;
350
  /// Function used for non-object declared property getters.
351
  LazyRuntimeFunction GetStructPropertyFn;
352
  /// Function used for non-object declared property setters.
353
  LazyRuntimeFunction SetStructPropertyFn;
354
355
  /// The version of the runtime that this class targets.  Must match the
356
  /// version in the runtime.
357
  int RuntimeVersion;
358
  /// The version of the protocol class.  Used to differentiate between ObjC1
359
  /// and ObjC2 protocols.  Objective-C 1 protocols can not contain optional
360
  /// components and can not contain declared properties.  We always emit
361
  /// Objective-C 2 property structures, but we have to pretend that they're
362
  /// Objective-C 1 property structures when targeting the GCC runtime or it
363
  /// will abort.
364
  const int ProtocolVersion;
365
366
  /// Generates an instance variable list structure.  This is a structure
367
  /// containing a size and an array of structures containing instance variable
368
  /// metadata.  This is used purely for introspection in the fragile ABI.  In
369
  /// the non-fragile ABI, it's used for instance variable fixup.
370
  llvm::Constant *GenerateIvarList(ArrayRef<llvm::Constant *> IvarNames,
371
                                   ArrayRef<llvm::Constant *> IvarTypes,
372
                                   ArrayRef<llvm::Constant *> IvarOffsets);
373
374
  /// Generates a method list structure.  This is a structure containing a size
375
  /// and an array of structures containing method metadata.
376
  ///
377
  /// This structure is used by both classes and categories, and contains a next
378
  /// pointer allowing them to be chained together in a linked list.
379
  llvm::Constant *GenerateMethodList(StringRef ClassName,
380
      StringRef CategoryName,
381
      ArrayRef<Selector> MethodSels,
382
      ArrayRef<llvm::Constant *> MethodTypes,
383
      bool isClassMethodList);
384
385
  /// Emits an empty protocol.  This is used for \@protocol() where no protocol
386
  /// is found.  The runtime will (hopefully) fix up the pointer to refer to the
387
  /// real protocol.
388
  llvm::Constant *GenerateEmptyProtocol(const std::string &ProtocolName);
389
390
  /// Generates a list of property metadata structures.  This follows the same
391
  /// pattern as method and instance variable metadata lists.
392
  llvm::Constant *GeneratePropertyList(const ObjCImplementationDecl *OID,
393
        SmallVectorImpl<Selector> &InstanceMethodSels,
394
        SmallVectorImpl<llvm::Constant*> &InstanceMethodTypes);
395
396
  /// Generates a list of referenced protocols.  Classes, categories, and
397
  /// protocols all use this structure.
398
  llvm::Constant *GenerateProtocolList(ArrayRef<std::string> Protocols);
399
400
  /// To ensure that all protocols are seen by the runtime, we add a category on
401
  /// a class defined in the runtime, declaring no methods, but adopting the
402
  /// protocols.  This is a horribly ugly hack, but it allows us to collect all
403
  /// of the protocols without changing the ABI.
404
  void GenerateProtocolHolderCategory();
405
406
  /// Generates a class structure.
407
  llvm::Constant *GenerateClassStructure(
408
      llvm::Constant *MetaClass,
409
      llvm::Constant *SuperClass,
410
      unsigned info,
411
      const char *Name,
412
      llvm::Constant *Version,
413
      llvm::Constant *InstanceSize,
414
      llvm::Constant *IVars,
415
      llvm::Constant *Methods,
416
      llvm::Constant *Protocols,
417
      llvm::Constant *IvarOffsets,
418
      llvm::Constant *Properties,
419
      llvm::Constant *StrongIvarBitmap,
420
      llvm::Constant *WeakIvarBitmap,
421
      bool isMeta=false);
422
423
  /// Generates a method list.  This is used by protocols to define the required
424
  /// and optional methods.
425
  llvm::Constant *GenerateProtocolMethodList(
426
      ArrayRef<llvm::Constant *> MethodNames,
427
      ArrayRef<llvm::Constant *> MethodTypes);
428
429
  /// Returns a selector with the specified type encoding.  An empty string is
430
  /// used to return an untyped selector (with the types field set to NULL).
431
  llvm::Value *GetSelector(CodeGenFunction &CGF, Selector Sel,
432
                           const std::string &TypeEncoding);
433
434
  /// Returns the variable used to store the offset of an instance variable.
435
  llvm::GlobalVariable *ObjCIvarOffsetVariable(const ObjCInterfaceDecl *ID,
436
      const ObjCIvarDecl *Ivar);
437
  /// Emits a reference to a class.  This allows the linker to object if there
438
  /// is no class of the matching name.
439
440
protected:
441
  void EmitClassRef(const std::string &className);
442
443
  /// Emits a pointer to the named class
444
  virtual llvm::Value *GetClassNamed(CodeGenFunction &CGF,
445
                                     const std::string &Name, bool isWeak);
446
447
  /// Looks up the method for sending a message to the specified object.  This
448
  /// mechanism differs between the GCC and GNU runtimes, so this method must be
449
  /// overridden in subclasses.
450
  virtual llvm::Value *LookupIMP(CodeGenFunction &CGF,
451
                                 llvm::Value *&Receiver,
452
                                 llvm::Value *cmd,
453
                                 llvm::MDNode *node,
454
                                 MessageSendInfo &MSI) = 0;
455
456
  /// Looks up the method for sending a message to a superclass.  This
457
  /// mechanism differs between the GCC and GNU runtimes, so this method must
458
  /// be overridden in subclasses.
459
  virtual llvm::Value *LookupIMPSuper(CodeGenFunction &CGF,
460
                                      Address ObjCSuper,
461
                                      llvm::Value *cmd,
462
                                      MessageSendInfo &MSI) = 0;
463
464
  /// Libobjc2 uses a bitfield representation where small(ish) bitfields are
465
  /// stored in a 64-bit value with the low bit set to 1 and the remaining 63
466
  /// bits set to their values, LSB first, while larger ones are stored in a
467
  /// structure of this / form:
468
  /// 
469
  /// struct { int32_t length; int32_t values[length]; };
470
  ///
471
  /// The values in the array are stored in host-endian format, with the least
472
  /// significant bit being assumed to come first in the bitfield.  Therefore,
473
  /// a bitfield with the 64th bit set will be (int64_t)&{ 2, [0, 1<<31] },
474
  /// while a bitfield / with the 63rd bit set will be 1<<64.
475
  llvm::Constant *MakeBitField(ArrayRef<bool> bits);
476
477
public:
478
  CGObjCGNU(CodeGenModule &cgm, unsigned runtimeABIVersion,
479
      unsigned protocolClassVersion);
480
481
  ConstantAddress GenerateConstantString(const StringLiteral *) override;
482
483
  RValue
484
  GenerateMessageSend(CodeGenFunction &CGF, ReturnValueSlot Return,
485
                      QualType ResultType, Selector Sel,
486
                      llvm::Value *Receiver, const CallArgList &CallArgs,
487
                      const ObjCInterfaceDecl *Class,
488
                      const ObjCMethodDecl *Method) override;
489
  RValue
490
  GenerateMessageSendSuper(CodeGenFunction &CGF, ReturnValueSlot Return,
491
                           QualType ResultType, Selector Sel,
492
                           const ObjCInterfaceDecl *Class,
493
                           bool isCategoryImpl, llvm::Value *Receiver,
494
                           bool IsClassMessage, const CallArgList &CallArgs,
495
                           const ObjCMethodDecl *Method) override;
496
  llvm::Value *GetClass(CodeGenFunction &CGF,
497
                        const ObjCInterfaceDecl *OID) override;
498
  llvm::Value *GetSelector(CodeGenFunction &CGF, Selector Sel) override;
499
  Address GetAddrOfSelector(CodeGenFunction &CGF, Selector Sel) override;
500
  llvm::Value *GetSelector(CodeGenFunction &CGF,
501
                           const ObjCMethodDecl *Method) override;
502
  llvm::Constant *GetEHType(QualType T) override;
503
504
  llvm::Function *GenerateMethod(const ObjCMethodDecl *OMD,
505
                                 const ObjCContainerDecl *CD) override;
506
  void GenerateCategory(const ObjCCategoryImplDecl *CMD) override;
507
  void GenerateClass(const ObjCImplementationDecl *ClassDecl) override;
508
  void RegisterAlias(const ObjCCompatibleAliasDecl *OAD) override;
509
  llvm::Value *GenerateProtocolRef(CodeGenFunction &CGF,
510
                                   const ObjCProtocolDecl *PD) override;
511
  void GenerateProtocol(const ObjCProtocolDecl *PD) override;
512
  llvm::Function *ModuleInitFunction() override;
513
  llvm::Constant *GetPropertyGetFunction() override;
514
  llvm::Constant *GetPropertySetFunction() override;
515
  llvm::Constant *GetOptimizedPropertySetFunction(bool atomic,
516
                                                  bool copy) override;
517
  llvm::Constant *GetSetStructFunction() override;
518
  llvm::Constant *GetGetStructFunction() override;
519
  llvm::Constant *GetCppAtomicObjectGetFunction() override;
520
  llvm::Constant *GetCppAtomicObjectSetFunction() override;
521
  llvm::Constant *EnumerationMutationFunction() override;
522
523
  void EmitTryStmt(CodeGenFunction &CGF,
524
                   const ObjCAtTryStmt &S) override;
525
  void EmitSynchronizedStmt(CodeGenFunction &CGF,
526
                            const ObjCAtSynchronizedStmt &S) override;
527
  void EmitThrowStmt(CodeGenFunction &CGF,
528
                     const ObjCAtThrowStmt &S,
529
                     bool ClearInsertionPoint=true) override;
530
  llvm::Value * EmitObjCWeakRead(CodeGenFunction &CGF,
531
                                 Address AddrWeakObj) override;
532
  void EmitObjCWeakAssign(CodeGenFunction &CGF,
533
                          llvm::Value *src, Address dst) override;
534
  void EmitObjCGlobalAssign(CodeGenFunction &CGF,
535
                            llvm::Value *src, Address dest,
536
                            bool threadlocal=false) override;
537
  void EmitObjCIvarAssign(CodeGenFunction &CGF, llvm::Value *src,
538
                          Address dest, llvm::Value *ivarOffset) override;
539
  void EmitObjCStrongCastAssign(CodeGenFunction &CGF,
540
                                llvm::Value *src, Address dest) override;
541
  void EmitGCMemmoveCollectable(CodeGenFunction &CGF, Address DestPtr,
542
                                Address SrcPtr,
543
                                llvm::Value *Size) override;
544
  LValue EmitObjCValueForIvar(CodeGenFunction &CGF, QualType ObjectTy,
545
                              llvm::Value *BaseValue, const ObjCIvarDecl *Ivar,
546
                              unsigned CVRQualifiers) override;
547
  llvm::Value *EmitIvarOffset(CodeGenFunction &CGF,
548
                              const ObjCInterfaceDecl *Interface,
549
                              const ObjCIvarDecl *Ivar) override;
550
  llvm::Value *EmitNSAutoreleasePoolClassRef(CodeGenFunction &CGF) override;
551
  llvm::Constant *BuildGCBlockLayout(CodeGenModule &CGM,
552
0
                                     const CGBlockInfo &blockInfo) override {
553
0
    return NULLPtr;
554
0
  }
555
  llvm::Constant *BuildRCBlockLayout(CodeGenModule &CGM,
556
0
                                     const CGBlockInfo &blockInfo) override {
557
0
    return NULLPtr;
558
0
  }
559
560
0
  llvm::Constant *BuildByrefLayout(CodeGenModule &CGM, QualType T) override {
561
0
    return NULLPtr;
562
0
  }
563
};
564
565
/// Class representing the legacy GCC Objective-C ABI.  This is the default when
566
/// -fobjc-nonfragile-abi is not specified.
567
///
568
/// The GCC ABI target actually generates code that is approximately compatible
569
/// with the new GNUstep runtime ABI, but refrains from using any features that
570
/// would not work with the GCC runtime.  For example, clang always generates
571
/// the extended form of the class structure, and the extra fields are simply
572
/// ignored by GCC libobjc.
573
class CGObjCGCC : public CGObjCGNU {
574
  /// The GCC ABI message lookup function.  Returns an IMP pointing to the
575
  /// method implementation for this message.
576
  LazyRuntimeFunction MsgLookupFn;
577
  /// The GCC ABI superclass message lookup function.  Takes a pointer to a
578
  /// structure describing the receiver and the class, and a selector as
579
  /// arguments.  Returns the IMP for the corresponding method.
580
  LazyRuntimeFunction MsgLookupSuperFn;
581
582
protected:
583
  llvm::Value *LookupIMP(CodeGenFunction &CGF, llvm::Value *&Receiver,
584
                         llvm::Value *cmd, llvm::MDNode *node,
585
9
                         MessageSendInfo &MSI) override {
586
9
    CGBuilderTy &Builder = CGF.Builder;
587
9
    llvm::Value *args[] = {
588
9
            EnforceType(Builder, Receiver, IdTy),
589
9
            EnforceType(Builder, cmd, SelectorTy) };
590
9
    llvm::CallSite imp = CGF.EmitRuntimeCallOrInvoke(MsgLookupFn, args);
591
9
    imp->setMetadata(msgSendMDKind, node);
592
9
    return imp.getInstruction();
593
9
  }
594
595
  llvm::Value *LookupIMPSuper(CodeGenFunction &CGF, Address ObjCSuper,
596
3
                              llvm::Value *cmd, MessageSendInfo &MSI) override {
597
3
    CGBuilderTy &Builder = CGF.Builder;
598
3
    llvm::Value *lookupArgs[] = {EnforceType(Builder, ObjCSuper,
599
3
        PtrToObjCSuperTy).getPointer(), cmd};
600
3
    return CGF.EmitNounwindRuntimeCall(MsgLookupSuperFn, lookupArgs);
601
3
  }
602
603
public:
604
11
  CGObjCGCC(CodeGenModule &Mod) : CGObjCGNU(Mod, 8, 2) {
605
11
    // IMP objc_msg_lookup(id, SEL);
606
11
    MsgLookupFn.init(&CGM, "objc_msg_lookup", IMPTy, IdTy, SelectorTy);
607
11
    // IMP objc_msg_lookup_super(struct objc_super*, SEL);
608
11
    MsgLookupSuperFn.init(&CGM, "objc_msg_lookup_super", IMPTy,
609
11
                          PtrToObjCSuperTy, SelectorTy);
610
11
  }
611
};
612
613
/// Class used when targeting the new GNUstep runtime ABI.
614
class CGObjCGNUstep : public CGObjCGNU {
615
    /// The slot lookup function.  Returns a pointer to a cacheable structure
616
    /// that contains (among other things) the IMP.
617
    LazyRuntimeFunction SlotLookupFn;
618
    /// The GNUstep ABI superclass message lookup function.  Takes a pointer to
619
    /// a structure describing the receiver and the class, and a selector as
620
    /// arguments.  Returns the slot for the corresponding method.  Superclass
621
    /// message lookup rarely changes, so this is a good caching opportunity.
622
    LazyRuntimeFunction SlotLookupSuperFn;
623
    /// Specialised function for setting atomic retain properties
624
    LazyRuntimeFunction SetPropertyAtomic;
625
    /// Specialised function for setting atomic copy properties
626
    LazyRuntimeFunction SetPropertyAtomicCopy;
627
    /// Specialised function for setting nonatomic retain properties
628
    LazyRuntimeFunction SetPropertyNonAtomic;
629
    /// Specialised function for setting nonatomic copy properties
630
    LazyRuntimeFunction SetPropertyNonAtomicCopy;
631
    /// Function to perform atomic copies of C++ objects with nontrivial copy
632
    /// constructors from Objective-C ivars.
633
    LazyRuntimeFunction CxxAtomicObjectGetFn;
634
    /// Function to perform atomic copies of C++ objects with nontrivial copy
635
    /// constructors to Objective-C ivars.
636
    LazyRuntimeFunction CxxAtomicObjectSetFn;
637
    /// Type of an slot structure pointer.  This is returned by the various
638
    /// lookup functions.
639
    llvm::Type *SlotTy;
640
641
  public:
642
    llvm::Constant *GetEHType(QualType T) override;
643
644
  protected:
645
    llvm::Value *LookupIMP(CodeGenFunction &CGF, llvm::Value *&Receiver,
646
                           llvm::Value *cmd, llvm::MDNode *node,
647
5
                           MessageSendInfo &MSI) override {
648
5
      CGBuilderTy &Builder = CGF.Builder;
649
5
      llvm::Function *LookupFn = SlotLookupFn;
650
5
651
5
      // Store the receiver on the stack so that we can reload it later
652
5
      Address ReceiverPtr =
653
5
        CGF.CreateTempAlloca(Receiver->getType(), CGF.getPointerAlign());
654
5
      Builder.CreateStore(Receiver, ReceiverPtr);
655
5
656
5
      llvm::Value *self;
657
5
658
5
      if (
isa<ObjCMethodDecl>(CGF.CurCodeDecl)5
) {
659
0
        self = CGF.LoadObjCSelf();
660
5
      } else {
661
5
        self = llvm::ConstantPointerNull::get(IdTy);
662
5
      }
663
5
664
5
      // The lookup function is guaranteed not to capture the receiver pointer.
665
5
      LookupFn->addParamAttr(0, llvm::Attribute::NoCapture);
666
5
667
5
      llvm::Value *args[] = {
668
5
              EnforceType(Builder, ReceiverPtr.getPointer(), PtrToIdTy),
669
5
              EnforceType(Builder, cmd, SelectorTy),
670
5
              EnforceType(Builder, self, IdTy) };
671
5
      llvm::CallSite slot = CGF.EmitRuntimeCallOrInvoke(LookupFn, args);
672
5
      slot.setOnlyReadsMemory();
673
5
      slot->setMetadata(msgSendMDKind, node);
674
5
675
5
      // Load the imp from the slot
676
5
      llvm::Value *imp = Builder.CreateAlignedLoad(
677
5
          Builder.CreateStructGEP(nullptr, slot.getInstruction(), 4),
678
5
          CGF.getPointerAlign());
679
5
680
5
      // The lookup function may have changed the receiver, so make sure we use
681
5
      // the new one.
682
5
      Receiver = Builder.CreateLoad(ReceiverPtr, true);
683
5
      return imp;
684
5
    }
685
686
    llvm::Value *LookupIMPSuper(CodeGenFunction &CGF, Address ObjCSuper,
687
                                llvm::Value *cmd,
688
0
                                MessageSendInfo &MSI) override {
689
0
      CGBuilderTy &Builder = CGF.Builder;
690
0
      llvm::Value *lookupArgs[] = {ObjCSuper.getPointer(), cmd};
691
0
692
0
      llvm::CallInst *slot =
693
0
        CGF.EmitNounwindRuntimeCall(SlotLookupSuperFn, lookupArgs);
694
0
      slot->setOnlyReadsMemory();
695
0
696
0
      return Builder.CreateAlignedLoad(Builder.CreateStructGEP(nullptr, slot, 4),
697
0
                                       CGF.getPointerAlign());
698
0
    }
699
700
  public:
701
7
    CGObjCGNUstep(CodeGenModule &Mod) : CGObjCGNU(Mod, 9, 3) {
702
7
      const ObjCRuntime &R = CGM.getLangOpts().ObjCRuntime;
703
7
704
7
      llvm::StructType *SlotStructTy =
705
7
          llvm::StructType::get(PtrTy, PtrTy, PtrTy, IntTy, IMPTy);
706
7
      SlotTy = llvm::PointerType::getUnqual(SlotStructTy);
707
7
      // Slot_t objc_msg_lookup_sender(id *receiver, SEL selector, id sender);
708
7
      SlotLookupFn.init(&CGM, "objc_msg_lookup_sender", SlotTy, PtrToIdTy,
709
7
                        SelectorTy, IdTy);
710
7
      // Slot_t objc_msg_lookup_super(struct objc_super*, SEL);
711
7
      SlotLookupSuperFn.init(&CGM, "objc_slot_lookup_super", SlotTy,
712
7
                             PtrToObjCSuperTy, SelectorTy);
713
7
      // If we're in ObjC++ mode, then we want to make 
714
7
      if (
CGM.getLangOpts().CPlusPlus7
) {
715
2
        llvm::Type *VoidTy = llvm::Type::getVoidTy(VMContext);
716
2
        // void *__cxa_begin_catch(void *e)
717
2
        EnterCatchFn.init(&CGM, "__cxa_begin_catch", PtrTy, PtrTy);
718
2
        // void __cxa_end_catch(void)
719
2
        ExitCatchFn.init(&CGM, "__cxa_end_catch", VoidTy);
720
2
        // void _Unwind_Resume_or_Rethrow(void*)
721
2
        ExceptionReThrowFn.init(&CGM, "_Unwind_Resume_or_Rethrow", VoidTy,
722
2
                                PtrTy);
723
7
      } else 
if (5
R.getVersion() >= VersionTuple(1, 7)5
) {
724
2
        llvm::Type *VoidTy = llvm::Type::getVoidTy(VMContext);
725
2
        // id objc_begin_catch(void *e)
726
2
        EnterCatchFn.init(&CGM, "objc_begin_catch", IdTy, PtrTy);
727
2
        // void objc_end_catch(void)
728
2
        ExitCatchFn.init(&CGM, "objc_end_catch", VoidTy);
729
2
        // void _Unwind_Resume_or_Rethrow(void*)
730
2
        ExceptionReThrowFn.init(&CGM, "objc_exception_rethrow", VoidTy, PtrTy);
731
2
      }
732
7
      llvm::Type *VoidTy = llvm::Type::getVoidTy(VMContext);
733
7
      SetPropertyAtomic.init(&CGM, "objc_setProperty_atomic", VoidTy, IdTy,
734
7
                             SelectorTy, IdTy, PtrDiffTy);
735
7
      SetPropertyAtomicCopy.init(&CGM, "objc_setProperty_atomic_copy", VoidTy,
736
7
                                 IdTy, SelectorTy, IdTy, PtrDiffTy);
737
7
      SetPropertyNonAtomic.init(&CGM, "objc_setProperty_nonatomic", VoidTy,
738
7
                                IdTy, SelectorTy, IdTy, PtrDiffTy);
739
7
      SetPropertyNonAtomicCopy.init(&CGM, "objc_setProperty_nonatomic_copy",
740
7
                                    VoidTy, IdTy, SelectorTy, IdTy, PtrDiffTy);
741
7
      // void objc_setCppObjectAtomic(void *dest, const void *src, void
742
7
      // *helper);
743
7
      CxxAtomicObjectSetFn.init(&CGM, "objc_setCppObjectAtomic", VoidTy, PtrTy,
744
7
                                PtrTy, PtrTy);
745
7
      // void objc_getCppObjectAtomic(void *dest, const void *src, void
746
7
      // *helper);
747
7
      CxxAtomicObjectGetFn.init(&CGM, "objc_getCppObjectAtomic", VoidTy, PtrTy,
748
7
                                PtrTy, PtrTy);
749
7
    }
750
751
2
    llvm::Constant *GetCppAtomicObjectGetFunction() override {
752
2
      // The optimised functions were added in version 1.7 of the GNUstep
753
2
      // runtime.
754
2
      assert (CGM.getLangOpts().ObjCRuntime.getVersion() >=
755
2
          VersionTuple(1, 7));
756
2
      return CxxAtomicObjectGetFn;
757
2
    }
758
759
2
    llvm::Constant *GetCppAtomicObjectSetFunction() override {
760
2
      // The optimised functions were added in version 1.7 of the GNUstep
761
2
      // runtime.
762
2
      assert (CGM.getLangOpts().ObjCRuntime.getVersion() >=
763
2
          VersionTuple(1, 7));
764
2
      return CxxAtomicObjectSetFn;
765
2
    }
766
767
    llvm::Constant *GetOptimizedPropertySetFunction(bool atomic,
768
4
                                                    bool copy) override {
769
4
      // The optimised property functions omit the GC check, and so are not
770
4
      // safe to use in GC mode.  The standard functions are fast in GC mode,
771
4
      // so there is less advantage in using them.
772
4
      assert ((CGM.getLangOpts().getGC() == LangOptions::NonGC));
773
4
      // The optimised functions were added in version 1.7 of the GNUstep
774
4
      // runtime.
775
4
      assert (CGM.getLangOpts().ObjCRuntime.getVersion() >=
776
4
          VersionTuple(1, 7));
777
4
778
4
      if (
atomic4
) {
779
2
        if (
copy2
)
return SetPropertyAtomicCopy1
;
780
1
        return SetPropertyAtomic;
781
1
      }
782
2
783
2
      
return copy ? 2
SetPropertyNonAtomicCopy1
:
SetPropertyNonAtomic1
;
784
4
    }
785
};
786
787
/// Support for the ObjFW runtime.
788
class CGObjCObjFW: public CGObjCGNU {
789
protected:
790
  /// The GCC ABI message lookup function.  Returns an IMP pointing to the
791
  /// method implementation for this message.
792
  LazyRuntimeFunction MsgLookupFn;
793
  /// stret lookup function.  While this does not seem to make sense at the
794
  /// first look, this is required to call the correct forwarding function.
795
  LazyRuntimeFunction MsgLookupFnSRet;
796
  /// The GCC ABI superclass message lookup function.  Takes a pointer to a
797
  /// structure describing the receiver and the class, and a selector as
798
  /// arguments.  Returns the IMP for the corresponding method.
799
  LazyRuntimeFunction MsgLookupSuperFn, MsgLookupSuperFnSRet;
800
801
  llvm::Value *LookupIMP(CodeGenFunction &CGF, llvm::Value *&Receiver,
802
                         llvm::Value *cmd, llvm::MDNode *node,
803
3
                         MessageSendInfo &MSI) override {
804
3
    CGBuilderTy &Builder = CGF.Builder;
805
3
    llvm::Value *args[] = {
806
3
            EnforceType(Builder, Receiver, IdTy),
807
3
            EnforceType(Builder, cmd, SelectorTy) };
808
3
809
3
    llvm::CallSite imp;
810
3
    if (CGM.ReturnTypeUsesSRet(MSI.CallInfo))
811
1
      imp = CGF.EmitRuntimeCallOrInvoke(MsgLookupFnSRet, args);
812
3
    else
813
2
      imp = CGF.EmitRuntimeCallOrInvoke(MsgLookupFn, args);
814
3
815
3
    imp->setMetadata(msgSendMDKind, node);
816
3
    return imp.getInstruction();
817
3
  }
818
819
  llvm::Value *LookupIMPSuper(CodeGenFunction &CGF, Address ObjCSuper,
820
0
                              llvm::Value *cmd, MessageSendInfo &MSI) override {
821
0
    CGBuilderTy &Builder = CGF.Builder;
822
0
    llvm::Value *lookupArgs[] = {
823
0
        EnforceType(Builder, ObjCSuper.getPointer(), PtrToObjCSuperTy), cmd,
824
0
    };
825
0
826
0
    if (CGM.ReturnTypeUsesSRet(MSI.CallInfo))
827
0
      return CGF.EmitNounwindRuntimeCall(MsgLookupSuperFnSRet, lookupArgs);
828
0
    else
829
0
      return CGF.EmitNounwindRuntimeCall(MsgLookupSuperFn, lookupArgs);
830
0
  }
831
832
  llvm::Value *GetClassNamed(CodeGenFunction &CGF, const std::string &Name,
833
3
                             bool isWeak) override {
834
3
    if (isWeak)
835
0
      return CGObjCGNU::GetClassNamed(CGF, Name, isWeak);
836
3
837
3
    EmitClassRef(Name);
838
3
    std::string SymbolName = "_OBJC_CLASS_" + Name;
839
3
    llvm::GlobalVariable *ClassSymbol = TheModule.getGlobalVariable(SymbolName);
840
3
    if (!ClassSymbol)
841
3
      ClassSymbol = new llvm::GlobalVariable(TheModule, LongTy, false,
842
3
                                             llvm::GlobalValue::ExternalLinkage,
843
3
                                             nullptr, SymbolName);
844
3
    return ClassSymbol;
845
3
  }
846
847
public:
848
5
  CGObjCObjFW(CodeGenModule &Mod): CGObjCGNU(Mod, 9, 3) {
849
5
    // IMP objc_msg_lookup(id, SEL);
850
5
    MsgLookupFn.init(&CGM, "objc_msg_lookup", IMPTy, IdTy, SelectorTy);
851
5
    MsgLookupFnSRet.init(&CGM, "objc_msg_lookup_stret", IMPTy, IdTy,
852
5
                         SelectorTy);
853
5
    // IMP objc_msg_lookup_super(struct objc_super*, SEL);
854
5
    MsgLookupSuperFn.init(&CGM, "objc_msg_lookup_super", IMPTy,
855
5
                          PtrToObjCSuperTy, SelectorTy);
856
5
    MsgLookupSuperFnSRet.init(&CGM, "objc_msg_lookup_super_stret", IMPTy,
857
5
                              PtrToObjCSuperTy, SelectorTy);
858
5
  }
859
};
860
} // end anonymous namespace
861
862
/// Emits a reference to a dummy variable which is emitted with each class.
863
/// This ensures that a linker error will be generated when trying to link
864
/// together modules where a referenced class is not defined.
865
12
void CGObjCGNU::EmitClassRef(const std::string &className) {
866
12
  std::string symbolRef = "__objc_class_ref_" + className;
867
12
  // Don't emit two copies of the same symbol
868
12
  if (TheModule.getGlobalVariable(symbolRef))
869
1
    return;
870
11
  std::string symbolName = "__objc_class_name_" + className;
871
11
  llvm::GlobalVariable *ClassSymbol = TheModule.getGlobalVariable(symbolName);
872
11
  if (
!ClassSymbol11
) {
873
7
    ClassSymbol = new llvm::GlobalVariable(TheModule, LongTy, false,
874
7
                                           llvm::GlobalValue::ExternalLinkage,
875
7
                                           nullptr, symbolName);
876
7
  }
877
12
  new llvm::GlobalVariable(TheModule, ClassSymbol->getType(), true,
878
12
    llvm::GlobalValue::WeakAnyLinkage, ClassSymbol, symbolRef);
879
12
}
880
881
static std::string SymbolNameForMethod( StringRef ClassName,
882
     StringRef CategoryName, const Selector MethodName,
883
56
    bool isClassMethod) {
884
56
  std::string MethodNameColonStripped = MethodName.getAsString();
885
56
  std::replace(MethodNameColonStripped.begin(), MethodNameColonStripped.end(),
886
56
      ':', '_');
887
56
  return (Twine(isClassMethod ? 
"_c_"2
:
"_i_"54
) + ClassName + "_" +
888
56
    CategoryName + "_" + MethodNameColonStripped).str();
889
56
}
890
891
CGObjCGNU::CGObjCGNU(CodeGenModule &cgm, unsigned runtimeABIVersion,
892
                     unsigned protocolClassVersion)
893
  : CGObjCRuntime(cgm), TheModule(CGM.getModule()),
894
    VMContext(cgm.getLLVMContext()), ClassPtrAlias(nullptr),
895
    MetaClassPtrAlias(nullptr), RuntimeVersion(runtimeABIVersion),
896
23
    ProtocolVersion(protocolClassVersion) {
897
23
898
23
  msgSendMDKind = VMContext.getMDKindID("GNUObjCMessageSend");
899
23
900
23
  CodeGenTypes &Types = CGM.getTypes();
901
23
  IntTy = cast<llvm::IntegerType>(
902
23
      Types.ConvertType(CGM.getContext().IntTy));
903
23
  LongTy = cast<llvm::IntegerType>(
904
23
      Types.ConvertType(CGM.getContext().LongTy));
905
23
  SizeTy = cast<llvm::IntegerType>(
906
23
      Types.ConvertType(CGM.getContext().getSizeType()));
907
23
  PtrDiffTy = cast<llvm::IntegerType>(
908
23
      Types.ConvertType(CGM.getContext().getPointerDiffType()));
909
23
  BoolTy = CGM.getTypes().ConvertType(CGM.getContext().BoolTy);
910
23
911
23
  Int8Ty = llvm::Type::getInt8Ty(VMContext);
912
23
  // C string type.  Used in lots of places.
913
23
  PtrToInt8Ty = llvm::PointerType::getUnqual(Int8Ty);
914
23
915
23
  Zeros[0] = llvm::ConstantInt::get(LongTy, 0);
916
23
  Zeros[1] = Zeros[0];
917
23
  NULLPtr = llvm::ConstantPointerNull::get(PtrToInt8Ty);
918
23
  // Get the selector Type.
919
23
  QualType selTy = CGM.getContext().getObjCSelType();
920
23
  if (
QualType() == selTy23
) {
921
0
    SelectorTy = PtrToInt8Ty;
922
23
  } else {
923
23
    SelectorTy = cast<llvm::PointerType>(CGM.getTypes().ConvertType(selTy));
924
23
  }
925
23
926
23
  PtrToIntTy = llvm::PointerType::getUnqual(IntTy);
927
23
  PtrTy = PtrToInt8Ty;
928
23
929
23
  Int32Ty = llvm::Type::getInt32Ty(VMContext);
930
23
  Int64Ty = llvm::Type::getInt64Ty(VMContext);
931
23
932
23
  IntPtrTy =
933
23
      CGM.getDataLayout().getPointerSizeInBits() == 32 ? 
Int32Ty4
:
Int64Ty19
;
934
23
935
23
  // Object type
936
23
  QualType UnqualIdTy = CGM.getContext().getObjCIdType();
937
23
  ASTIdTy = CanQualType();
938
23
  if (
UnqualIdTy != QualType()23
) {
939
23
    ASTIdTy = CGM.getContext().getCanonicalType(UnqualIdTy);
940
23
    IdTy = cast<llvm::PointerType>(CGM.getTypes().ConvertType(ASTIdTy));
941
23
  } else {
942
0
    IdTy = PtrToInt8Ty;
943
0
  }
944
23
  PtrToIdTy = llvm::PointerType::getUnqual(IdTy);
945
23
946
23
  ObjCSuperTy = llvm::StructType::get(IdTy, IdTy);
947
23
  PtrToObjCSuperTy = llvm::PointerType::getUnqual(ObjCSuperTy);
948
23
949
23
  llvm::Type *VoidTy = llvm::Type::getVoidTy(VMContext);
950
23
951
23
  // void objc_exception_throw(id);
952
23
  ExceptionThrowFn.init(&CGM, "objc_exception_throw", VoidTy, IdTy);
953
23
  ExceptionReThrowFn.init(&CGM, "objc_exception_throw", VoidTy, IdTy);
954
23
  // int objc_sync_enter(id);
955
23
  SyncEnterFn.init(&CGM, "objc_sync_enter", IntTy, IdTy);
956
23
  // int objc_sync_exit(id);
957
23
  SyncExitFn.init(&CGM, "objc_sync_exit", IntTy, IdTy);
958
23
959
23
  // void objc_enumerationMutation (id)
960
23
  EnumerationMutationFn.init(&CGM, "objc_enumerationMutation", VoidTy, IdTy);
961
23
962
23
  // id objc_getProperty(id, SEL, ptrdiff_t, BOOL)
963
23
  GetPropertyFn.init(&CGM, "objc_getProperty", IdTy, IdTy, SelectorTy,
964
23
                     PtrDiffTy, BoolTy);
965
23
  // void objc_setProperty(id, SEL, ptrdiff_t, id, BOOL, BOOL)
966
23
  SetPropertyFn.init(&CGM, "objc_setProperty", VoidTy, IdTy, SelectorTy,
967
23
                     PtrDiffTy, IdTy, BoolTy, BoolTy);
968
23
  // void objc_setPropertyStruct(void*, void*, ptrdiff_t, BOOL, BOOL)
969
23
  GetStructPropertyFn.init(&CGM, "objc_getPropertyStruct", VoidTy, PtrTy, PtrTy,
970
23
                           PtrDiffTy, BoolTy, BoolTy);
971
23
  // void objc_setPropertyStruct(void*, void*, ptrdiff_t, BOOL, BOOL)
972
23
  SetStructPropertyFn.init(&CGM, "objc_setPropertyStruct", VoidTy, PtrTy, PtrTy,
973
23
                           PtrDiffTy, BoolTy, BoolTy);
974
23
975
23
  // IMP type
976
23
  llvm::Type *IMPArgs[] = { IdTy, SelectorTy };
977
23
  IMPTy = llvm::PointerType::getUnqual(llvm::FunctionType::get(IdTy, IMPArgs,
978
23
              true));
979
23
980
23
  const LangOptions &Opts = CGM.getLangOpts();
981
23
  if (
(Opts.getGC() != LangOptions::NonGC) || 23
Opts.ObjCAutoRefCount23
)
982
1
    RuntimeVersion = 10;
983
23
984
23
  // Don't bother initialising the GC stuff unless we're compiling in GC mode
985
23
  if (
Opts.getGC() != LangOptions::NonGC23
) {
986
0
    // This is a bit of an hack.  We should sort this out by having a proper
987
0
    // CGObjCGNUstep subclass for GC, but we may want to really support the old
988
0
    // ABI and GC added in ObjectiveC2.framework, so we fudge it a bit for now
989
0
    // Get selectors needed in GC mode
990
0
    RetainSel = GetNullarySelector("retain", CGM.getContext());
991
0
    ReleaseSel = GetNullarySelector("release", CGM.getContext());
992
0
    AutoreleaseSel = GetNullarySelector("autorelease", CGM.getContext());
993
0
994
0
    // Get functions needed in GC mode
995
0
996
0
    // id objc_assign_ivar(id, id, ptrdiff_t);
997
0
    IvarAssignFn.init(&CGM, "objc_assign_ivar", IdTy, IdTy, IdTy, PtrDiffTy);
998
0
    // id objc_assign_strongCast (id, id*)
999
0
    StrongCastAssignFn.init(&CGM, "objc_assign_strongCast", IdTy, IdTy,
1000
0
                            PtrToIdTy);
1001
0
    // id objc_assign_global(id, id*);
1002
0
    GlobalAssignFn.init(&CGM, "objc_assign_global", IdTy, IdTy, PtrToIdTy);
1003
0
    // id objc_assign_weak(id, id*);
1004
0
    WeakAssignFn.init(&CGM, "objc_assign_weak", IdTy, IdTy, PtrToIdTy);
1005
0
    // id objc_read_weak(id*);
1006
0
    WeakReadFn.init(&CGM, "objc_read_weak", IdTy, PtrToIdTy);
1007
0
    // void *objc_memmove_collectable(void*, void *, size_t);
1008
0
    MemMoveFn.init(&CGM, "objc_memmove_collectable", PtrTy, PtrTy, PtrTy,
1009
0
                   SizeTy);
1010
0
  }
1011
23
}
1012
1013
llvm::Value *CGObjCGNU::GetClassNamed(CodeGenFunction &CGF,
1014
2
                                      const std::string &Name, bool isWeak) {
1015
2
  llvm::Constant *ClassName = MakeConstantString(Name);
1016
2
  // With the incompatible ABI, this will need to be replaced with a direct
1017
2
  // reference to the class symbol.  For the compatible nonfragile ABI we are
1018
2
  // still performing this lookup at run time but emitting the symbol for the
1019
2
  // class externally so that we can make the switch later.
1020
2
  //
1021
2
  // Libobjc2 contains an LLVM pass that replaces calls to objc_lookup_class
1022
2
  // with memoized versions or with static references if it's safe to do so.
1023
2
  if (!isWeak)
1024
2
    EmitClassRef(Name);
1025
2
1026
2
  llvm::Constant *ClassLookupFn =
1027
2
    CGM.CreateRuntimeFunction(llvm::FunctionType::get(IdTy, PtrToInt8Ty, true),
1028
2
                              "objc_lookup_class");
1029
2
  return CGF.EmitNounwindRuntimeCall(ClassLookupFn, ClassName);
1030
2
}
1031
1032
// This has to perform the lookup every time, since posing and related
1033
// techniques can modify the name -> class mapping.
1034
llvm::Value *CGObjCGNU::GetClass(CodeGenFunction &CGF,
1035
5
                                 const ObjCInterfaceDecl *OID) {
1036
5
  auto *Value =
1037
5
      GetClassNamed(CGF, OID->getNameAsString(), OID->isWeakImported());
1038
5
  if (
CGM.getTriple().isOSBinFormatCOFF()5
) {
1039
1
    if (auto *
ClassSymbol1
= dyn_cast<llvm::GlobalVariable>(Value)) {
1040
1
      auto DLLStorage = llvm::GlobalValue::DefaultStorageClass;
1041
1
      if (OID->hasAttr<DLLExportAttr>())
1042
0
        DLLStorage = llvm::GlobalValue::DLLExportStorageClass;
1043
1
      else 
if (1
OID->hasAttr<DLLImportAttr>()1
)
1044
1
        DLLStorage = llvm::GlobalValue::DLLImportStorageClass;
1045
1
      ClassSymbol->setDLLStorageClass(DLLStorage);
1046
1
    }
1047
1
  }
1048
5
  return Value;
1049
5
}
1050
1051
0
llvm::Value *CGObjCGNU::EmitNSAutoreleasePoolClassRef(CodeGenFunction &CGF) {
1052
0
  auto *Value  = GetClassNamed(CGF, "NSAutoreleasePool", false);
1053
0
  if (
CGM.getTriple().isOSBinFormatCOFF()0
) {
1054
0
    if (auto *
ClassSymbol0
= dyn_cast<llvm::GlobalVariable>(Value)) {
1055
0
      IdentifierInfo &II = CGF.CGM.getContext().Idents.get("NSAutoreleasePool");
1056
0
      TranslationUnitDecl *TUDecl = CGM.getContext().getTranslationUnitDecl();
1057
0
      DeclContext *DC = TranslationUnitDecl::castToDeclContext(TUDecl);
1058
0
1059
0
      const VarDecl *VD = nullptr;
1060
0
      for (const auto &Result : DC->lookup(&II))
1061
0
        
if (0
(VD = dyn_cast<VarDecl>(Result))0
)
1062
0
          break;
1063
0
1064
0
      auto DLLStorage = llvm::GlobalValue::DefaultStorageClass;
1065
0
      if (
!VD || 0
VD->hasAttr<DLLImportAttr>()0
)
1066
0
        DLLStorage = llvm::GlobalValue::DLLImportStorageClass;
1067
0
      else 
if (0
VD->hasAttr<DLLExportAttr>()0
)
1068
0
        DLLStorage = llvm::GlobalValue::DLLExportStorageClass;
1069
0
1070
0
      ClassSymbol->setDLLStorageClass(DLLStorage);
1071
0
    }
1072
0
  }
1073
0
  return Value;
1074
0
}
1075
1076
llvm::Value *CGObjCGNU::GetSelector(CodeGenFunction &CGF, Selector Sel,
1077
22
                                    const std::string &TypeEncoding) {
1078
22
  SmallVectorImpl<TypedSelector> &Types = SelectorTable[Sel];
1079
22
  llvm::GlobalAlias *SelValue = nullptr;
1080
22
1081
22
  for (SmallVectorImpl<TypedSelector>::iterator i = Types.begin(),
1082
22
      e = Types.end() ; 
i!=e22
;
i++0
) {
1083
3
    if (
i->first == TypeEncoding3
) {
1084
3
      SelValue = i->second;
1085
3
      break;
1086
3
    }
1087
3
  }
1088
22
  if (
!SelValue22
) {
1089
19
    SelValue = llvm::GlobalAlias::create(
1090
19
        SelectorTy->getElementType(), 0, llvm::GlobalValue::PrivateLinkage,
1091
19
        ".objc_selector_" + Sel.getAsString(), &TheModule);
1092
19
    Types.emplace_back(TypeEncoding, SelValue);
1093
19
  }
1094
22
1095
22
  return SelValue;
1096
22
}
1097
1098
0
Address CGObjCGNU::GetAddrOfSelector(CodeGenFunction &CGF, Selector Sel) {
1099
0
  llvm::Value *SelValue = GetSelector(CGF, Sel);
1100
0
1101
0
  // Store it to a temporary.  Does this satisfy the semantics of
1102
0
  // GetAddrOfSelector?  Hopefully.
1103
0
  Address tmp = CGF.CreateTempAlloca(SelValue->getType(),
1104
0
                                     CGF.getPointerAlign());
1105
0
  CGF.Builder.CreateStore(SelValue, tmp);
1106
0
  return tmp;
1107
0
}
1108
1109
17
llvm::Value *CGObjCGNU::GetSelector(CodeGenFunction &CGF, Selector Sel) {
1110
17
  return GetSelector(CGF, Sel, std::string());
1111
17
}
1112
1113
llvm::Value *CGObjCGNU::GetSelector(CodeGenFunction &CGF,
1114
5
                                    const ObjCMethodDecl *Method) {
1115
5
  std::string SelTypes = CGM.getContext().getObjCEncodingForMethodDecl(Method);
1116
5
  return GetSelector(CGF, Method->getSelector(), SelTypes);
1117
5
}
1118
1119
15
llvm::Constant *CGObjCGNU::GetEHType(QualType T) {
1120
15
  if (
T->isObjCIdType() || 15
T->isObjCQualifiedIdType()14
) {
1121
1
    // With the old ABI, there was only one kind of catchall, which broke
1122
1
    // foreign exceptions.  With the new ABI, we use __objc_id_typeinfo as
1123
1
    // a pointer indicating object catchalls, and NULL to indicate real
1124
1
    // catchalls
1125
1
    if (
CGM.getLangOpts().ObjCRuntime.isNonFragile()1
) {
1126
1
      return MakeConstantString("@id");
1127
0
    } else {
1128
0
      return nullptr;
1129
0
    }
1130
14
  }
1131
14
1132
14
  // All other types should be Objective-C interface pointer types.
1133
14
  const ObjCObjectPointerType *OPT = T->getAs<ObjCObjectPointerType>();
1134
14
  assert(OPT && "Invalid @catch type.");
1135
14
  const ObjCInterfaceDecl *IDecl = OPT->getObjectType()->getInterface();
1136
14
  assert(IDecl && "Invalid @catch type.");
1137
14
  return MakeConstantString(IDecl->getIdentifier()->getName());
1138
14
}
1139
1140
1
llvm::Constant *CGObjCGNUstep::GetEHType(QualType T) {
1141
1
  if (!CGM.getLangOpts().CPlusPlus)
1142
1
    return CGObjCGNU::GetEHType(T);
1143
0
1144
0
  // For Objective-C++, we want to provide the ability to catch both C++ and
1145
0
  // Objective-C objects in the same function.
1146
0
1147
0
  // There's a particular fixed type info for 'id'.
1148
0
  
if (0
T->isObjCIdType() ||
1149
0
      
T->isObjCQualifiedIdType()0
) {
1150
0
    llvm::Constant *IDEHType =
1151
0
      CGM.getModule().getGlobalVariable("__objc_id_type_info");
1152
0
    if (!IDEHType)
1153
0
      IDEHType =
1154
0
        new llvm::GlobalVariable(CGM.getModule(), PtrToInt8Ty,
1155
0
                                 false,
1156
0
                                 llvm::GlobalValue::ExternalLinkage,
1157
0
                                 nullptr, "__objc_id_type_info");
1158
0
    return llvm::ConstantExpr::getBitCast(IDEHType, PtrToInt8Ty);
1159
0
  }
1160
0
1161
0
  const ObjCObjectPointerType *PT =
1162
0
    T->getAs<ObjCObjectPointerType>();
1163
0
  assert(PT && "Invalid @catch type.");
1164
0
  const ObjCInterfaceType *IT = PT->getInterfaceType();
1165
0
  assert(IT && "Invalid @catch type.");
1166
0
  std::string className = IT->getDecl()->getIdentifier()->getName();
1167
0
1168
0
  std::string typeinfoName = "__objc_eh_typeinfo_" + className;
1169
0
1170
0
  // Return the existing typeinfo if it exists
1171
0
  llvm::Constant *typeinfo = TheModule.getGlobalVariable(typeinfoName);
1172
0
  if (typeinfo)
1173
0
    return llvm::ConstantExpr::getBitCast(typeinfo, PtrToInt8Ty);
1174
0
1175
0
  // Otherwise create it.
1176
0
1177
0
  // vtable for gnustep::libobjc::__objc_class_type_info
1178
0
  // It's quite ugly hard-coding this.  Ideally we'd generate it using the host
1179
0
  // platform's name mangling.
1180
0
  const char *vtableName = "_ZTVN7gnustep7libobjc22__objc_class_type_infoE";
1181
0
  auto *Vtable = TheModule.getGlobalVariable(vtableName);
1182
0
  if (
!Vtable0
) {
1183
0
    Vtable = new llvm::GlobalVariable(TheModule, PtrToInt8Ty, true,
1184
0
                                      llvm::GlobalValue::ExternalLinkage,
1185
0
                                      nullptr, vtableName);
1186
0
  }
1187
1
  llvm::Constant *Two = llvm::ConstantInt::get(IntTy, 2);
1188
1
  auto *BVtable = llvm::ConstantExpr::getBitCast(
1189
1
      llvm::ConstantExpr::getGetElementPtr(Vtable->getValueType(), Vtable, Two),
1190
1
      PtrToInt8Ty);
1191
1
1192
1
  llvm::Constant *typeName =
1193
1
    ExportUniqueString(className, "__objc_eh_typename_");
1194
1
1195
1
  ConstantInitBuilder builder(CGM);
1196
1
  auto fields = builder.beginStruct();
1197
1
  fields.add(BVtable);
1198
1
  fields.add(typeName);
1199
1
  llvm::Constant *TI =
1200
1
    fields.finishAndCreateGlobal("__objc_eh_typeinfo_" + className,
1201
1
                                 CGM.getPointerAlign(),
1202
1
                                 /*constant*/ false,
1203
1
                                 llvm::GlobalValue::LinkOnceODRLinkage);
1204
1
  return llvm::ConstantExpr::getBitCast(TI, PtrToInt8Ty);
1205
1
}
1206
1207
/// Generate an NSConstantString object.
1208
3
ConstantAddress CGObjCGNU::GenerateConstantString(const StringLiteral *SL) {
1209
3
1210
3
  std::string Str = SL->getString().str();
1211
3
  CharUnits Align = CGM.getPointerAlign();
1212
3
1213
3
  // Look for an existing one
1214
3
  llvm::StringMap<llvm::Constant*>::iterator old = ObjCStrings.find(Str);
1215
3
  if (old != ObjCStrings.end())
1216
0
    return ConstantAddress(old->getValue(), Align);
1217
3
1218
3
  StringRef StringClass = CGM.getLangOpts().ObjCConstantStringClass;
1219
3
1220
3
  if (
StringClass.empty()3
)
StringClass = "NXConstantString"2
;
1221
3
1222
3
  std::string Sym = "_OBJC_CLASS_";
1223
3
  Sym += StringClass;
1224
3
1225
3
  llvm::Constant *isa = TheModule.getNamedGlobal(Sym);
1226
3
1227
3
  if (!isa)
1228
3
    isa = new llvm::GlobalVariable(TheModule, IdTy, /* isConstant */false,
1229
3
            llvm::GlobalValue::ExternalWeakLinkage, nullptr, Sym);
1230
0
  else 
if (0
isa->getType() != PtrToIdTy0
)
1231
0
    isa = llvm::ConstantExpr::getBitCast(isa, PtrToIdTy);
1232
3
1233
3
  ConstantInitBuilder Builder(CGM);
1234
3
  auto Fields = Builder.beginStruct();
1235
3
  Fields.add(isa);
1236
3
  Fields.add(MakeConstantString(Str));
1237
3
  Fields.addInt(IntTy, Str.size());
1238
3
  llvm::Constant *ObjCStr =
1239
3
    Fields.finishAndCreateGlobal(".objc_str", Align);
1240
3
  ObjCStr = llvm::ConstantExpr::getBitCast(ObjCStr, PtrToInt8Ty);
1241
3
  ObjCStrings[Str] = ObjCStr;
1242
3
  ConstantStrings.push_back(ObjCStr);
1243
3
  return ConstantAddress(ObjCStr, Align);
1244
3
}
1245
1246
///Generates a message send where the super is the receiver.  This is a message
1247
///send to self with special delivery semantics indicating which class's method
1248
///should be called.
1249
RValue
1250
CGObjCGNU::GenerateMessageSendSuper(CodeGenFunction &CGF,
1251
                                    ReturnValueSlot Return,
1252
                                    QualType ResultType,
1253
                                    Selector Sel,
1254
                                    const ObjCInterfaceDecl *Class,
1255
                                    bool isCategoryImpl,
1256
                                    llvm::Value *Receiver,
1257
                                    bool IsClassMessage,
1258
                                    const CallArgList &CallArgs,
1259
3
                                    const ObjCMethodDecl *Method) {
1260
3
  CGBuilderTy &Builder = CGF.Builder;
1261
3
  if (
CGM.getLangOpts().getGC() == LangOptions::GCOnly3
) {
1262
0
    if (
Sel == RetainSel || 0
Sel == AutoreleaseSel0
) {
1263
0
      return RValue::get(EnforceType(Builder, Receiver,
1264
0
                  CGM.getTypes().ConvertType(ResultType)));
1265
0
    }
1266
0
    
if (0
Sel == ReleaseSel0
) {
1267
0
      return RValue::get(nullptr);
1268
0
    }
1269
3
  }
1270
3
1271
3
  llvm::Value *cmd = GetSelector(CGF, Sel);
1272
3
  CallArgList ActualArgs;
1273
3
1274
3
  ActualArgs.add(RValue::get(EnforceType(Builder, Receiver, IdTy)), ASTIdTy);
1275
3
  ActualArgs.add(RValue::get(cmd), CGF.getContext().getObjCSelType());
1276
3
  ActualArgs.addFrom(CallArgs);
1277
3
1278
3
  MessageSendInfo MSI = getMessageSendInfo(Method, ResultType, ActualArgs);
1279
3
1280
3
  llvm::Value *ReceiverClass = nullptr;
1281
3
  if (
isCategoryImpl3
) {
1282
0
    llvm::Constant *classLookupFunction = nullptr;
1283
0
    if (
IsClassMessage0
) {
1284
0
      classLookupFunction = CGM.CreateRuntimeFunction(llvm::FunctionType::get(
1285
0
            IdTy, PtrTy, true), "objc_get_meta_class");
1286
0
    } else {
1287
0
      classLookupFunction = CGM.CreateRuntimeFunction(llvm::FunctionType::get(
1288
0
            IdTy, PtrTy, true), "objc_get_class");
1289
0
    }
1290
0
    ReceiverClass = Builder.CreateCall(classLookupFunction,
1291
0
        MakeConstantString(Class->getNameAsString()));
1292
3
  } else {
1293
3
    // Set up global aliases for the metaclass or class pointer if they do not
1294
3
    // already exist.  These will are forward-references which will be set to
1295
3
    // pointers to the class and metaclass structure created for the runtime
1296
3
    // load function.  To send a message to super, we look up the value of the
1297
3
    // super_class pointer from either the class or metaclass structure.
1298
3
    if (
IsClassMessage3
) {
1299
1
      if (
!MetaClassPtrAlias1
) {
1300
1
        MetaClassPtrAlias = llvm::GlobalAlias::create(
1301
1
            IdTy->getElementType(), 0, llvm::GlobalValue::InternalLinkage,
1302
1
            ".objc_metaclass_ref" + Class->getNameAsString(), &TheModule);
1303
1
      }
1304
1
      ReceiverClass = MetaClassPtrAlias;
1305
3
    } else {
1306
2
      if (
!ClassPtrAlias2
) {
1307
1
        ClassPtrAlias = llvm::GlobalAlias::create(
1308
1
            IdTy->getElementType(), 0, llvm::GlobalValue::InternalLinkage,
1309
1
            ".objc_class_ref" + Class->getNameAsString(), &TheModule);
1310
1
      }
1311
2
      ReceiverClass = ClassPtrAlias;
1312
2
    }
1313
3
  }
1314
3
  // Cast the pointer to a simplified version of the class structure
1315
3
  llvm::Type *CastTy = llvm::StructType::get(IdTy, IdTy);
1316
3
  ReceiverClass = Builder.CreateBitCast(ReceiverClass,
1317
3
                                        llvm::PointerType::getUnqual(CastTy));
1318
3
  // Get the superclass pointer
1319
3
  ReceiverClass = Builder.CreateStructGEP(CastTy, ReceiverClass, 1);
1320
3
  // Load the superclass pointer
1321
3
  ReceiverClass =
1322
3
    Builder.CreateAlignedLoad(ReceiverClass, CGF.getPointerAlign());
1323
3
  // Construct the structure used to look up the IMP
1324
3
  llvm::StructType *ObjCSuperTy =
1325
3
      llvm::StructType::get(Receiver->getType(), IdTy);
1326
3
1327
3
  // FIXME: Is this really supposed to be a dynamic alloca?
1328
3
  Address ObjCSuper = Address(Builder.CreateAlloca(ObjCSuperTy),
1329
3
                              CGF.getPointerAlign());
1330
3
1331
3
  Builder.CreateStore(Receiver,
1332
3
                   Builder.CreateStructGEP(ObjCSuper, 0, CharUnits::Zero()));
1333
3
  Builder.CreateStore(ReceiverClass,
1334
3
                   Builder.CreateStructGEP(ObjCSuper, 1, CGF.getPointerSize()));
1335
3
1336
3
  ObjCSuper = EnforceType(Builder, ObjCSuper, PtrToObjCSuperTy);
1337
3
1338
3
  // Get the IMP
1339
3
  llvm::Value *imp = LookupIMPSuper(CGF, ObjCSuper, cmd, MSI);
1340
3
  imp = EnforceType(Builder, imp, MSI.MessengerType);
1341
3
1342
3
  llvm::Metadata *impMD[] = {
1343
3
      llvm::MDString::get(VMContext, Sel.getAsString()),
1344
3
      llvm::MDString::get(VMContext, Class->getSuperClass()->getNameAsString()),
1345
3
      llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
1346
3
          llvm::Type::getInt1Ty(VMContext), IsClassMessage))};
1347
3
  llvm::MDNode *node = llvm::MDNode::get(VMContext, impMD);
1348
3
1349
3
  CGCallee callee(CGCalleeInfo(), imp);
1350
3
1351
3
  llvm::Instruction *call;
1352
3
  RValue msgRet = CGF.EmitCall(MSI.CallInfo, callee, Return, ActualArgs, &call);
1353
3
  call->setMetadata(msgSendMDKind, node);
1354
3
  return msgRet;
1355
3
}
1356
1357
/// Generate code for a message send expression.
1358
RValue
1359
CGObjCGNU::GenerateMessageSend(CodeGenFunction &CGF,
1360
                               ReturnValueSlot Return,
1361
                               QualType ResultType,
1362
                               Selector Sel,
1363
                               llvm::Value *Receiver,
1364
                               const CallArgList &CallArgs,
1365
                               const ObjCInterfaceDecl *Class,
1366
17
                               const ObjCMethodDecl *Method) {
1367
17
  CGBuilderTy &Builder = CGF.Builder;
1368
17
1369
17
  // Strip out message sends to retain / release in GC mode
1370
17
  if (
CGM.getLangOpts().getGC() == LangOptions::GCOnly17
) {
1371
0
    if (
Sel == RetainSel || 0
Sel == AutoreleaseSel0
) {
1372
0
      return RValue::get(EnforceType(Builder, Receiver,
1373
0
                  CGM.getTypes().ConvertType(ResultType)));
1374
0
    }
1375
0
    
if (0
Sel == ReleaseSel0
) {
1376
0
      return RValue::get(nullptr);
1377
0
    }
1378
17
  }
1379
17
1380
17
  // If the return type is something that goes in an integer register, the
1381
17
  // runtime will handle 0 returns.  For other cases, we fill in the 0 value
1382
17
  // ourselves.
1383
17
  //
1384
17
  // The language spec says the result of this kind of message send is
1385
17
  // undefined, but lots of people seem to have forgotten to read that
1386
17
  // paragraph and insist on sending messages to nil that have structure
1387
17
  // returns.  With GCC, this generates a random return value (whatever happens
1388
17
  // to be on the stack / in those registers at the time) on most platforms,
1389
17
  // and generates an illegal instruction trap on SPARC.  With LLVM it corrupts
1390
17
  // the stack.  
1391
17
  bool isPointerSizedReturn = (ResultType->isAnyPointerType() ||
1392
17
      
ResultType->isIntegralOrEnumerationType()5
||
ResultType->isVoidType()3
);
1393
17
1394
17
  llvm::BasicBlock *startBB = nullptr;
1395
17
  llvm::BasicBlock *messageBB = nullptr;
1396
17
  llvm::BasicBlock *continueBB = nullptr;
1397
17
1398
17
  if (
!isPointerSizedReturn17
) {
1399
2
    startBB = Builder.GetInsertBlock();
1400
2
    messageBB = CGF.createBasicBlock("msgSend");
1401
2
    continueBB = CGF.createBasicBlock("continue");
1402
2
1403
2
    llvm::Value *isNil = Builder.CreateICmpEQ(Receiver, 
1404
2
            llvm::Constant::getNullValue(Receiver->getType()));
1405
2
    Builder.CreateCondBr(isNil, continueBB, messageBB);
1406
2
    CGF.EmitBlock(messageBB);
1407
2
  }
1408
17
1409
17
  IdTy = cast<llvm::PointerType>(CGM.getTypes().ConvertType(ASTIdTy));
1410
17
  llvm::Value *cmd;
1411
17
  if (Method)
1412
5
    cmd = GetSelector(CGF, Method);
1413
17
  else
1414
12
    cmd = GetSelector(CGF, Sel);
1415
17
  cmd = EnforceType(Builder, cmd, SelectorTy);
1416
17
  Receiver = EnforceType(Builder, Receiver, IdTy);
1417
17
1418
17
  llvm::Metadata *impMD[] = {
1419
17
      llvm::MDString::get(VMContext, Sel.getAsString()),
1420
17
      llvm::MDString::get(VMContext, Class ? 
Class->getNameAsString()5
:
""12
),
1421
17
      llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
1422
17
          llvm::Type::getInt1Ty(VMContext), Class != nullptr))};
1423
17
  llvm::MDNode *node = llvm::MDNode::get(VMContext, impMD);
1424
17
1425
17
  CallArgList ActualArgs;
1426
17
  ActualArgs.add(RValue::get(Receiver), ASTIdTy);
1427
17
  ActualArgs.add(RValue::get(cmd), CGF.getContext().getObjCSelType());
1428
17
  ActualArgs.addFrom(CallArgs);
1429
17
1430
17
  MessageSendInfo MSI = getMessageSendInfo(Method, ResultType, ActualArgs);
1431
17
1432
17
  // Get the IMP to call
1433
17
  llvm::Value *imp;
1434
17
1435
17
  // If we have non-legacy dispatch specified, we try using the objc_msgSend()
1436
17
  // functions.  These are not supported on all platforms (or all runtimes on a
1437
17
  // given platform), so we 
1438
17
  switch (CGM.getCodeGenOpts().getObjCDispatchMethod()) {
1439
17
    case CodeGenOptions::Legacy:
1440
17
      imp = LookupIMP(CGF, Receiver, cmd, node, MSI);
1441
17
      break;
1442
0
    case CodeGenOptions::Mixed:
1443
0
    case CodeGenOptions::NonLegacy:
1444
0
      if (
CGM.ReturnTypeUsesFPRet(ResultType)0
) {
1445
0
        imp = CGM.CreateRuntimeFunction(llvm::FunctionType::get(IdTy, IdTy, true),
1446
0
                                  "objc_msgSend_fpret");
1447
0
      } else 
if (0
CGM.ReturnTypeUsesSRet(MSI.CallInfo)0
) {
1448
0
        // The actual types here don't matter - we're going to bitcast the
1449
0
        // function anyway
1450
0
        imp = CGM.CreateRuntimeFunction(llvm::FunctionType::get(IdTy, IdTy, true),
1451
0
                                  "objc_msgSend_stret");
1452
0
      } else {
1453
0
        imp = CGM.CreateRuntimeFunction(llvm::FunctionType::get(IdTy, IdTy, true),
1454
0
                                  "objc_msgSend");
1455
0
      }
1456
17
  }
1457
17
1458
17
  // Reset the receiver in case the lookup modified it
1459
17
  ActualArgs[0] = CallArg(RValue::get(Receiver), ASTIdTy, false);
1460
17
1461
17
  imp = EnforceType(Builder, imp, MSI.MessengerType);
1462
17
1463
17
  llvm::Instruction *call;
1464
17
  CGCallee callee(CGCalleeInfo(), imp);
1465
17
  RValue msgRet = CGF.EmitCall(MSI.CallInfo, callee, Return, ActualArgs, &call);
1466
17
  call->setMetadata(msgSendMDKind, node);
1467
17
1468
17
1469
17
  if (
!isPointerSizedReturn17
) {
1470
2
    messageBB = CGF.Builder.GetInsertBlock();
1471
2
    CGF.Builder.CreateBr(continueBB);
1472
2
    CGF.EmitBlock(continueBB);
1473
2
    if (
msgRet.isScalar()2
) {
1474
0
      llvm::Value *v = msgRet.getScalarVal();
1475
0
      llvm::PHINode *phi = Builder.CreatePHI(v->getType(), 2);
1476
0
      phi->addIncoming(v, messageBB);
1477
0
      phi->addIncoming(llvm::Constant::getNullValue(v->getType()), startBB);
1478
0
      msgRet = RValue::get(phi);
1479
2
    } else 
if (2
msgRet.isAggregate()2
) {
1480
2
      Address v = msgRet.getAggregateAddress();
1481
2
      llvm::PHINode *phi = Builder.CreatePHI(v.getType(), 2);
1482
2
      llvm::Type *RetTy = v.getElementType();
1483
2
      Address NullVal = CGF.CreateTempAlloca(RetTy, v.getAlignment(), "null");
1484
2
      CGF.InitTempAlloca(NullVal, llvm::Constant::getNullValue(RetTy));
1485
2
      phi->addIncoming(v.getPointer(), messageBB);
1486
2
      phi->addIncoming(NullVal.getPointer(), startBB);
1487
2
      msgRet = RValue::getAggregate(Address(phi, v.getAlignment()));
1488
2
    } else /* isComplex() */ {
1489
0
      std::pair<llvm::Value*,llvm::Value*> v = msgRet.getComplexVal();
1490
0
      llvm::PHINode *phi = Builder.CreatePHI(v.first->getType(), 2);
1491
0
      phi->addIncoming(v.first, messageBB);
1492
0
      phi->addIncoming(llvm::Constant::getNullValue(v.first->getType()),
1493
0
          startBB);
1494
0
      llvm::PHINode *phi2 = Builder.CreatePHI(v.second->getType(), 2);
1495
0
      phi2->addIncoming(v.second, messageBB);
1496
0
      phi2->addIncoming(llvm::Constant::getNullValue(v.second->getType()),
1497
0
          startBB);
1498
0
      msgRet = RValue::getComplex(phi, phi2);
1499
0
    }
1500
2
  }
1501
17
  return msgRet;
1502
17
}
1503
1504
/// Generates a MethodList.  Used in construction of a objc_class and
1505
/// objc_category structures.
1506
llvm::Constant *CGObjCGNU::
1507
GenerateMethodList(StringRef ClassName,
1508
                   StringRef CategoryName,
1509
                   ArrayRef<Selector> MethodSels,
1510
                   ArrayRef<llvm::Constant *> MethodTypes,
1511
70
                   bool isClassMethodList) {
1512
70
  if (MethodSels.empty())
1513
62
    return NULLPtr;
1514
8
1515
8
  ConstantInitBuilder Builder(CGM);
1516
8
1517
8
  auto MethodList = Builder.beginStruct();
1518
8
  MethodList.addNullPointer(CGM.Int8PtrTy);
1519
8
  MethodList.addInt(Int32Ty, MethodTypes.size());
1520
8
1521
8
  // Get the method structure type.
1522
8
  llvm::StructType *ObjCMethodTy =
1523
8
    llvm::StructType::get(CGM.getLLVMContext(), {
1524
8
      PtrToInt8Ty, // Really a selector, but the runtime creates it us.
1525
8
      PtrToInt8Ty, // Method types
1526
8
      IMPTy        // Method pointer
1527
8
    });
1528
8
  auto Methods = MethodList.beginArray();
1529
36
  for (unsigned int i = 0, e = MethodTypes.size(); 
i < e36
;
++i28
) {
1530
28
    llvm::Constant *FnPtr =
1531
28
      TheModule.getFunction(SymbolNameForMethod(ClassName, CategoryName,
1532
28
                                                MethodSels[i],
1533
28
                                                isClassMethodList));
1534
28
    assert(FnPtr && "Can't generate metadata for method that doesn't exist");
1535
28
    auto Method = Methods.beginStruct(ObjCMethodTy);
1536
28
    Method.add(MakeConstantString(MethodSels[i].getAsString()));
1537
28
    Method.add(MethodTypes[i]);
1538
28
    Method.addBitCast(FnPtr, IMPTy);
1539
28
    Method.finishAndAddTo(Methods);
1540
28
  }
1541
70
  Methods.finishAndAddTo(MethodList);
1542
70
1543
70
  // Create an instance of the structure
1544
70
  return MethodList.finishAndCreateGlobal(".objc_method_list",
1545
70
                                          CGM.getPointerAlign());
1546
70
}
1547
1548
/// Generates an IvarList.  Used in construction of a objc_class.
1549
llvm::Constant *CGObjCGNU::
1550
GenerateIvarList(ArrayRef<llvm::Constant *> IvarNames,
1551
                 ArrayRef<llvm::Constant *> IvarTypes,
1552
32
                 ArrayRef<llvm::Constant *> IvarOffsets) {
1553
32
  if (IvarNames.empty())
1554
20
    return NULLPtr;
1555
12
1556
12
  ConstantInitBuilder Builder(CGM);
1557
12
1558
12
  // Structure containing array count followed by array.
1559
12
  auto IvarList = Builder.beginStruct();
1560
12
  IvarList.addInt(IntTy, (int)IvarNames.size());
1561
12
1562
12
  // Get the ivar structure type.
1563
12
  llvm::StructType *ObjCIvarTy =
1564
12
      llvm::StructType::get(PtrToInt8Ty, PtrToInt8Ty, IntTy);
1565
12
1566
12
  // Array of ivar structures.
1567
12
  auto Ivars = IvarList.beginArray(ObjCIvarTy);
1568
38
  for (unsigned int i = 0, e = IvarNames.size() ; 
i < e38
;
i++26
) {
1569
26
    auto Ivar = Ivars.beginStruct(ObjCIvarTy);
1570
26
    Ivar.add(IvarNames[i]);
1571
26
    Ivar.add(IvarTypes[i]);
1572
26
    Ivar.add(IvarOffsets[i]);
1573
26
    Ivar.finishAndAddTo(Ivars);
1574
26
  }
1575
32
  Ivars.finishAndAddTo(IvarList);
1576
32
1577
32
  // Create an instance of the structure
1578
32
  return IvarList.finishAndCreateGlobal(".objc_ivar_list",
1579
32
                                        CGM.getPointerAlign());
1580
32
}
1581
1582
/// Generate a class structure
1583
llvm::Constant *CGObjCGNU::GenerateClassStructure(
1584
    llvm::Constant *MetaClass,
1585
    llvm::Constant *SuperClass,
1586
    unsigned info,
1587
    const char *Name,
1588
    llvm::Constant *Version,
1589
    llvm::Constant *InstanceSize,
1590
    llvm::Constant *IVars,
1591
    llvm::Constant *Methods,
1592
    llvm::Constant *Protocols,
1593
    llvm::Constant *IvarOffsets,
1594
    llvm::Constant *Properties,
1595
    llvm::Constant *StrongIvarBitmap,
1596
    llvm::Constant *WeakIvarBitmap,
1597
32
    bool isMeta) {
1598
32
  // Set up the class structure
1599
32
  // Note:  Several of these are char*s when they should be ids.  This is
1600
32
  // because the runtime performs this translation on load.
1601
32
  //
1602
32
  // Fields marked New ABI are part of the GNUstep runtime.  We emit them
1603
32
  // anyway; the classes will still work with the GNU runtime, they will just
1604
32
  // be ignored.
1605
32
  llvm::StructType *ClassTy = llvm::StructType::get(
1606
32
      PtrToInt8Ty,        // isa
1607
32
      PtrToInt8Ty,        // super_class
1608
32
      PtrToInt8Ty,        // name
1609
32
      LongTy,             // version
1610
32
      LongTy,             // info
1611
32
      LongTy,             // instance_size
1612
32
      IVars->getType(),   // ivars
1613
32
      Methods->getType(), // methods
1614
32
      // These are all filled in by the runtime, so we pretend
1615
32
      PtrTy, // dtable
1616
32
      PtrTy, // subclass_list
1617
32
      PtrTy, // sibling_class
1618
32
      PtrTy, // protocols
1619
32
      PtrTy, // gc_object_type
1620
32
      // New ABI:
1621
32
      LongTy,                 // abi_version
1622
32
      IvarOffsets->getType(), // ivar_offsets
1623
32
      Properties->getType(),  // properties
1624
32
      IntPtrTy,               // strong_pointers
1625
32
      IntPtrTy                // weak_pointers
1626
32
      );
1627
32
1628
32
  ConstantInitBuilder Builder(CGM);
1629
32
  auto Elements = Builder.beginStruct(ClassTy);
1630
32
1631
32
  // Fill in the structure
1632
32
1633
32
  // isa 
1634
32
  Elements.addBitCast(MetaClass, PtrToInt8Ty);
1635
32
  // super_class
1636
32
  Elements.add(SuperClass);
1637
32
  // name
1638
32
  Elements.add(MakeConstantString(Name, ".class_name"));
1639
32
  // version
1640
32
  Elements.addInt(LongTy, 0);
1641
32
  // info
1642
32
  Elements.addInt(LongTy, info);
1643
32
  // instance_size
1644
32
  if (
isMeta32
) {
1645
16
    llvm::DataLayout td(&TheModule);
1646
16
    Elements.addInt(LongTy,
1647
16
                    td.getTypeSizeInBits(ClassTy) /
1648
16
                      CGM.getContext().getCharWidth());
1649
16
  } else
1650
16
    Elements.add(InstanceSize);
1651
32
  // ivars
1652
32
  Elements.add(IVars);
1653
32
  // methods
1654
32
  Elements.add(Methods);
1655
32
  // These are all filled in by the runtime, so we pretend
1656
32
  // dtable
1657
32
  Elements.add(NULLPtr);
1658
32
  // subclass_list
1659
32
  Elements.add(NULLPtr);
1660
32
  // sibling_class
1661
32
  Elements.add(NULLPtr);
1662
32
  // protocols
1663
32
  Elements.addBitCast(Protocols, PtrTy);
1664
32
  // gc_object_type
1665
32
  Elements.add(NULLPtr);
1666
32
  // abi_version
1667
32
  Elements.addInt(LongTy, 1);
1668
32
  // ivar_offsets
1669
32
  Elements.add(IvarOffsets);
1670
32
  // properties
1671
32
  Elements.add(Properties);
1672
32
  // strong_pointers
1673
32
  Elements.add(StrongIvarBitmap);
1674
32
  // weak_pointers
1675
32
  Elements.add(WeakIvarBitmap);
1676
32
  // Create an instance of the structure
1677
32
  // This is now an externally visible symbol, so that we can speed up class
1678
32
  // messages in the next ABI.  We may already have some weak references to
1679
32
  // this, so check and fix them properly.
1680
32
  std::string ClassSym((isMeta ? 
"_OBJC_METACLASS_"16
:
"_OBJC_CLASS_"16
) +
1681
32
          std::string(Name));
1682
32
  llvm::GlobalVariable *ClassRef = TheModule.getNamedGlobal(ClassSym);
1683
32
  llvm::Constant *Class =
1684
32
    Elements.finishAndCreateGlobal(ClassSym, CGM.getPointerAlign(), false,
1685
32
                                   llvm::GlobalValue::ExternalLinkage);
1686
32
  if (
ClassRef32
) {
1687
0
    ClassRef->replaceAllUsesWith(llvm::ConstantExpr::getBitCast(Class,
1688
0
                  ClassRef->getType()));
1689
0
    ClassRef->removeFromParent();
1690
0
    Class->setName(ClassSym);
1691
0
  }
1692
32
  return Class;
1693
32
}
1694
1695
llvm::Constant *CGObjCGNU::
1696
GenerateProtocolMethodList(ArrayRef<llvm::Constant *> MethodNames,
1697
9
                           ArrayRef<llvm::Constant *> MethodTypes) {
1698
9
  // Get the method structure type.
1699
9
  llvm::StructType *ObjCMethodDescTy =
1700
9
    llvm::StructType::get(CGM.getLLVMContext(), { PtrToInt8Ty, PtrToInt8Ty });
1701
9
  ConstantInitBuilder Builder(CGM);
1702
9
  auto MethodList = Builder.beginStruct();
1703
9
  MethodList.addInt(IntTy, MethodNames.size());
1704
9
  auto Methods = MethodList.beginArray(ObjCMethodDescTy);
1705
10
  for (unsigned int i = 0, e = MethodTypes.size() ; 
i < e10
;
i++1
) {
1706
1
    auto Method = Methods.beginStruct(ObjCMethodDescTy);
1707
1
    Method.add(MethodNames[i]);
1708
1
    Method.add(MethodTypes[i]);
1709
1
    Method.finishAndAddTo(Methods);
1710
1
  }
1711
9
  Methods.finishAndAddTo(MethodList);
1712
9
  return MethodList.finishAndCreateGlobal(".objc_method_list",
1713
9
                                          CGM.getPointerAlign());
1714
9
}
1715
1716
// Create the protocol list structure used in classes, categories and so on
1717
llvm::Constant *
1718
20
CGObjCGNU::GenerateProtocolList(ArrayRef<std::string> Protocols) {
1719
20
1720
20
  ConstantInitBuilder Builder(CGM);
1721
20
  auto ProtocolList = Builder.beginStruct();
1722
20
  ProtocolList.add(NULLPtr);
1723
20
  ProtocolList.addInt(LongTy, Protocols.size());
1724
20
1725
20
  auto Elements = ProtocolList.beginArray(PtrToInt8Ty);
1726
20
  for (const std::string *iter = Protocols.begin(), *endIter = Protocols.end();
1727
22
      
iter != endIter22
;
iter++2
) {
1728
2
    llvm::Constant *protocol = nullptr;
1729
2
    llvm::StringMap<llvm::Constant*>::iterator value =
1730
2
      ExistingProtocols.find(*iter);
1731
2
    if (
value == ExistingProtocols.end()2
) {
1732
1
      protocol = GenerateEmptyProtocol(*iter);
1733
2
    } else {
1734
1
      protocol = value->getValue();
1735
1
    }
1736
2
    Elements.addBitCast(protocol, PtrToInt8Ty);
1737
2
  }
1738
20
  Elements.finishAndAddTo(ProtocolList);
1739
20
  return ProtocolList.finishAndCreateGlobal(".objc_protocol_list",
1740
20
                                            CGM.getPointerAlign());
1741
20
}
1742
1743
llvm::Value *CGObjCGNU::GenerateProtocolRef(CodeGenFunction &CGF,
1744
0
                                            const ObjCProtocolDecl *PD) {
1745
0
  llvm::Value *protocol = ExistingProtocols[PD->getNameAsString()];
1746
0
  llvm::Type *T =
1747
0
    CGM.getTypes().ConvertType(CGM.getContext().getObjCProtoType());
1748
0
  return CGF.Builder.CreateBitCast(protocol, llvm::PointerType::getUnqual(T));
1749
0
}
1750
1751
llvm::Constant *
1752
1
CGObjCGNU::GenerateEmptyProtocol(const std::string &ProtocolName) {
1753
1
  llvm::Constant *ProtocolList = GenerateProtocolList({});
1754
1
  llvm::Constant *MethodList = GenerateProtocolMethodList({}, {});
1755
1
  // Protocols are objects containing lists of the methods implemented and
1756
1
  // protocols adopted.
1757
1
  ConstantInitBuilder Builder(CGM);
1758
1
  auto Elements = Builder.beginStruct();
1759
1
1760
1
  // The isa pointer must be set to a magic number so the runtime knows it's
1761
1
  // the correct layout.
1762
1
  Elements.add(llvm::ConstantExpr::getIntToPtr(
1763
1
          llvm::ConstantInt::get(Int32Ty, ProtocolVersion), IdTy));
1764
1
1765
1
  Elements.add(MakeConstantString(ProtocolName, ".objc_protocol_name"));
1766
1
  Elements.add(ProtocolList);
1767
1
  Elements.add(MethodList);
1768
1
  Elements.add(MethodList);
1769
1
  Elements.add(MethodList);
1770
1
  Elements.add(MethodList);
1771
1
  return Elements.finishAndCreateGlobal(".objc_protocol",
1772
1
                                        CGM.getPointerAlign());
1773
1
}
1774
1775
2
void CGObjCGNU::GenerateProtocol(const ObjCProtocolDecl *PD) {
1776
2
  ASTContext &Context = CGM.getContext();
1777
2
  std::string ProtocolName = PD->getNameAsString();
1778
2
  
1779
2
  // Use the protocol definition, if there is one.
1780
2
  if (const ObjCProtocolDecl *Def = PD->getDefinition())
1781
2
    PD = Def;
1782
2
1783
2
  SmallVector<std::string, 16> Protocols;
1784
2
  for (const auto *PI : PD->protocols())
1785
0
    Protocols.push_back(PI->getNameAsString());
1786
2
  SmallVector<llvm::Constant*, 16> InstanceMethodNames;
1787
2
  SmallVector<llvm::Constant*, 16> InstanceMethodTypes;
1788
2
  SmallVector<llvm::Constant*, 16> OptionalInstanceMethodNames;
1789
2
  SmallVector<llvm::Constant*, 16> OptionalInstanceMethodTypes;
1790
1
  for (const auto *I : PD->instance_methods()) {
1791
1
    std::string TypeStr = Context.getObjCEncodingForMethodDecl(I);
1792
1
    if (
I->getImplementationControl() == ObjCMethodDecl::Optional1
) {
1793
0
      OptionalInstanceMethodNames.push_back(
1794
0
          MakeConstantString(I->getSelector().getAsString()));
1795
0
      OptionalInstanceMethodTypes.push_back(MakeConstantString(TypeStr));
1796
1
    } else {
1797
1
      InstanceMethodNames.push_back(
1798
1
          MakeConstantString(I->getSelector().getAsString()));
1799
1
      InstanceMethodTypes.push_back(MakeConstantString(TypeStr));
1800
1
    }
1801
1
  }
1802
2
  // Collect information about class methods:
1803
2
  SmallVector<llvm::Constant*, 16> ClassMethodNames;
1804
2
  SmallVector<llvm::Constant*, 16> ClassMethodTypes;
1805
2
  SmallVector<llvm::Constant*, 16> OptionalClassMethodNames;
1806
2
  SmallVector<llvm::Constant*, 16> OptionalClassMethodTypes;
1807
0
  for (const auto *I : PD->class_methods()) {
1808
0
    std::string TypeStr = Context.getObjCEncodingForMethodDecl(I);
1809
0
    if (
I->getImplementationControl() == ObjCMethodDecl::Optional0
) {
1810
0
      OptionalClassMethodNames.push_back(
1811
0
          MakeConstantString(I->getSelector().getAsString()));
1812
0
      OptionalClassMethodTypes.push_back(MakeConstantString(TypeStr));
1813
0
    } else {
1814
0
      ClassMethodNames.push_back(
1815
0
          MakeConstantString(I->getSelector().getAsString()));
1816
0
      ClassMethodTypes.push_back(MakeConstantString(TypeStr));
1817
0
    }
1818
0
  }
1819
2
1820
2
  llvm::Constant *ProtocolList = GenerateProtocolList(Protocols);
1821
2
  llvm::Constant *InstanceMethodList =
1822
2
    GenerateProtocolMethodList(InstanceMethodNames, InstanceMethodTypes);
1823
2
  llvm::Constant *ClassMethodList =
1824
2
    GenerateProtocolMethodList(ClassMethodNames, ClassMethodTypes);
1825
2
  llvm::Constant *OptionalInstanceMethodList =
1826
2
    GenerateProtocolMethodList(OptionalInstanceMethodNames,
1827
2
            OptionalInstanceMethodTypes);
1828
2
  llvm::Constant *OptionalClassMethodList =
1829
2
    GenerateProtocolMethodList(OptionalClassMethodNames,
1830
2
            OptionalClassMethodTypes);
1831
2
1832
2
  // Property metadata: name, attributes, isSynthesized, setter name, setter
1833
2
  // types, getter name, getter types.
1834
2
  // The isSynthesized value is always set to 0 in a protocol.  It exists to
1835
2
  // simplify the runtime library by allowing it to use the same data
1836
2
  // structures for protocol metadata everywhere.
1837
2
1838
2
  llvm::Constant *PropertyList;
1839
2
  llvm::Constant *OptionalPropertyList;
1840
2
  {
1841
2
    llvm::StructType *propertyMetadataTy =
1842
2
      llvm::StructType::get(CGM.getLLVMContext(),
1843
2
        { PtrToInt8Ty, Int8Ty, Int8Ty, Int8Ty, Int8Ty, PtrToInt8Ty,
1844
2
          PtrToInt8Ty, PtrToInt8Ty, PtrToInt8Ty });
1845
2
1846
2
    unsigned numReqProperties = 0, numOptProperties = 0;
1847
0
    for (auto property : PD->instance_properties()) {
1848
0
      if (property->isOptional())
1849
0
        numOptProperties++;
1850
0
      else
1851
0
        numReqProperties++;
1852
0
    }
1853
2
1854
2
    ConstantInitBuilder reqPropertyListBuilder(CGM);
1855
2
    auto reqPropertiesList = reqPropertyListBuilder.beginStruct();
1856
2
    reqPropertiesList.addInt(IntTy, numReqProperties);
1857
2
    reqPropertiesList.add(NULLPtr);
1858
2
    auto reqPropertiesArray = reqPropertiesList.beginArray(propertyMetadataTy);
1859
2
1860
2
    ConstantInitBuilder optPropertyListBuilder(CGM);
1861
2
    auto optPropertiesList = optPropertyListBuilder.beginStruct();
1862
2
    optPropertiesList.addInt(IntTy, numOptProperties);
1863
2
    optPropertiesList.add(NULLPtr);
1864
2
    auto optPropertiesArray = optPropertiesList.beginArray(propertyMetadataTy);
1865
2
1866
2
    // Add all of the property methods need adding to the method list and to the
1867
2
    // property metadata list.
1868
0
    for (auto *property : PD->instance_properties()) {
1869
0
      auto &propertiesArray =
1870
0
        (property->isOptional() ? 
optPropertiesArray0
:
reqPropertiesArray0
);
1871
0
      auto fields = propertiesArray.beginStruct(propertyMetadataTy);
1872
0
1873
0
      fields.add(MakePropertyEncodingString(property, nullptr));
1874
0
      PushPropertyAttributes(fields, property);
1875
0
1876
0
      if (ObjCMethodDecl *
getter0
= property->getGetterMethodDecl()) {
1877
0
        std::string typeStr = Context.getObjCEncodingForMethodDecl(getter);
1878
0
        llvm::Constant *typeEncoding = MakeConstantString(typeStr);
1879
0
        InstanceMethodTypes.push_back(typeEncoding);
1880
0
        fields.add(MakeConstantString(getter->getSelector().getAsString()));
1881
0
        fields.add(typeEncoding);
1882
0
      } else {
1883
0
        fields.add(NULLPtr);
1884
0
        fields.add(NULLPtr);
1885
0
      }
1886
0
      if (ObjCMethodDecl *
setter0
= property->getSetterMethodDecl()) {
1887
0
        std::string typeStr = Context.getObjCEncodingForMethodDecl(setter);
1888
0
        llvm::Constant *typeEncoding = MakeConstantString(typeStr);
1889
0
        InstanceMethodTypes.push_back(typeEncoding);
1890
0
        fields.add(MakeConstantString(setter->getSelector().getAsString()));
1891
0
        fields.add(typeEncoding);
1892
0
      } else {
1893
0
        fields.add(NULLPtr);
1894
0
        fields.add(NULLPtr);
1895
0
      }
1896
0
1897
0
      fields.finishAndAddTo(propertiesArray);
1898
0
    }
1899
2
1900
2
    reqPropertiesArray.finishAndAddTo(reqPropertiesList);
1901
2
    PropertyList =
1902
2
      reqPropertiesList.finishAndCreateGlobal(".objc_property_list",
1903
2
                                              CGM.getPointerAlign());
1904
2
1905
2
    optPropertiesArray.finishAndAddTo(optPropertiesList);
1906
2
    OptionalPropertyList =
1907
2
      optPropertiesList.finishAndCreateGlobal(".objc_property_list",
1908
2
                                              CGM.getPointerAlign());
1909
2
  }
1910
2
1911
2
  // Protocols are objects containing lists of the methods implemented and
1912
2
  // protocols adopted.
1913
2
  // The isa pointer must be set to a magic number so the runtime knows it's
1914
2
  // the correct layout.
1915
2
  ConstantInitBuilder Builder(CGM);
1916
2
  auto Elements = Builder.beginStruct();
1917
2
  Elements.add(
1918
2
      llvm::ConstantExpr::getIntToPtr(
1919
2
          llvm::ConstantInt::get(Int32Ty, ProtocolVersion), IdTy));
1920
2
  Elements.add(
1921
2
      MakeConstantString(ProtocolName, ".objc_protocol_name"));
1922
2
  Elements.add(ProtocolList);
1923
2
  Elements.add(InstanceMethodList);
1924
2
  Elements.add(ClassMethodList);
1925
2
  Elements.add(OptionalInstanceMethodList);
1926
2
  Elements.add(OptionalClassMethodList);
1927
2
  Elements.add(PropertyList);
1928
2
  Elements.add(OptionalPropertyList);
1929
2
  ExistingProtocols[ProtocolName] =
1930
2
    llvm::ConstantExpr::getBitCast(
1931
2
      Elements.finishAndCreateGlobal(".objc_protocol", CGM.getPointerAlign()),
1932
2
      IdTy);
1933
2
}
1934
18
void CGObjCGNU::GenerateProtocolHolderCategory() {
1935
18
  // Collect information about instance methods
1936
18
  SmallVector<Selector, 1> MethodSels;
1937
18
  SmallVector<llvm::Constant*, 1> MethodTypes;
1938
18
1939
18
  ConstantInitBuilder Builder(CGM);
1940
18
  auto Elements = Builder.beginStruct();
1941
18
1942
18
  const std::string ClassName = "__ObjC_Protocol_Holder_Ugly_Hack";
1943
18
  const std::string CategoryName = "AnotherHack";
1944
18
  Elements.add(MakeConstantString(CategoryName));
1945
18
  Elements.add(MakeConstantString(ClassName));
1946
18
  // Instance method list
1947
18
  Elements.addBitCast(GenerateMethodList(
1948
18
          ClassName, CategoryName, MethodSels, MethodTypes, false), PtrTy);
1949
18
  // Class method list
1950
18
  Elements.addBitCast(GenerateMethodList(
1951
18
          ClassName, CategoryName, MethodSels, MethodTypes, true), PtrTy);
1952
18
1953
18
  // Protocol list
1954
18
  ConstantInitBuilder ProtocolListBuilder(CGM);
1955
18
  auto ProtocolList = ProtocolListBuilder.beginStruct();
1956
18
  ProtocolList.add(NULLPtr);
1957
18
  ProtocolList.addInt(LongTy, ExistingProtocols.size());
1958
18
  auto ProtocolElements = ProtocolList.beginArray(PtrTy);
1959
18
  for (auto iter = ExistingProtocols.begin(), endIter = ExistingProtocols.end();
1960
20
       
iter != endIter20
;
iter++2
) {
1961
2
    ProtocolElements.addBitCast(iter->getValue(), PtrTy);
1962
2
  }
1963
18
  ProtocolElements.finishAndAddTo(ProtocolList);
1964
18
  Elements.addBitCast(
1965
18
                   ProtocolList.finishAndCreateGlobal(".objc_protocol_list",
1966
18
                                                      CGM.getPointerAlign()),
1967
18
                   PtrTy);
1968
18
  Categories.push_back(llvm::ConstantExpr::getBitCast(
1969
18
        Elements.finishAndCreateGlobal("", CGM.getPointerAlign()),
1970
18
        PtrTy));
1971
18
}
1972
1973
/// Libobjc2 uses a bitfield representation where small(ish) bitfields are
1974
/// stored in a 64-bit value with the low bit set to 1 and the remaining 63
1975
/// bits set to their values, LSB first, while larger ones are stored in a
1976
/// structure of this / form:
1977
/// 
1978
/// struct { int32_t length; int32_t values[length]; };
1979
///
1980
/// The values in the array are stored in host-endian format, with the least
1981
/// significant bit being assumed to come first in the bitfield.  Therefore, a
1982
/// bitfield with the 64th bit set will be (int64_t)&{ 2, [0, 1<<31] }, while a
1983
/// bitfield / with the 63rd bit set will be 1<<64.
1984
32
llvm::Constant *CGObjCGNU::MakeBitField(ArrayRef<bool> bits) {
1985
32
  int bitCount = bits.size();
1986
32
  int ptrBits = CGM.getDataLayout().getPointerSizeInBits();
1987
32
  if (
bitCount < ptrBits32
) {
1988
32
    uint64_t val = 1;
1989
84
    for (int i=0 ; 
i<bitCount84
;
++i52
) {
1990
52
      if (
bits[i]52
)
val |= 1ULL<<(i+1)0
;
1991
52
    }
1992
32
    return llvm::ConstantInt::get(IntPtrTy, val);
1993
32
  }
1994
0
  SmallVector<llvm::Constant *, 8> values;
1995
0
  int v=0;
1996
0
  while (
v < bitCount0
) {
1997
0
    int32_t word = 0;
1998
0
    for (int i=0 ; 
(i<32) && 0
(v<bitCount)0
;
++i0
) {
1999
0
      if (
bits[v]0
)
word |= 1<<i0
;
2000
0
      v++;
2001
0
    }
2002
0
    values.push_back(llvm::ConstantInt::get(Int32Ty, word));
2003
0
  }
2004
0
2005
0
  ConstantInitBuilder builder(CGM);
2006
0
  auto fields = builder.beginStruct();
2007
0
  fields.addInt(Int32Ty, values.size());
2008
0
  auto array = fields.beginArray();
2009
0
  for (auto v : values) array.add(v);
2010
32
  array.finishAndAddTo(fields);
2011
32
2012
32
  llvm::Constant *GS =
2013
32
    fields.finishAndCreateGlobal("", CharUnits::fromQuantity(4));
2014
32
  llvm::Constant *ptr = llvm::ConstantExpr::getPtrToInt(GS, IntPtrTy);
2015
32
  return ptr;
2016
32
}
2017
2018
1
void CGObjCGNU::GenerateCategory(const ObjCCategoryImplDecl *OCD) {
2019
1
  std::string ClassName = OCD->getClassInterface()->getNameAsString();
2020
1
  std::string CategoryName = OCD->getNameAsString();
2021
1
  // Collect information about instance methods
2022
1
  SmallVector<Selector, 16> InstanceMethodSels;
2023
1
  SmallVector<llvm::Constant*, 16> InstanceMethodTypes;
2024
0
  for (const auto *I : OCD->instance_methods()) {
2025
0
    InstanceMethodSels.push_back(I->getSelector());
2026
0
    std::string TypeStr = CGM.getContext().getObjCEncodingForMethodDecl(I);
2027
0
    InstanceMethodTypes.push_back(MakeConstantString(TypeStr));
2028
0
  }
2029
1
2030
1
  // Collect information about class methods
2031
1
  SmallVector<Selector, 16> ClassMethodSels;
2032
1
  SmallVector<llvm::Constant*, 16> ClassMethodTypes;
2033
0
  for (const auto *I : OCD->class_methods()) {
2034
0
    ClassMethodSels.push_back(I->getSelector());
2035
0
    std::string TypeStr = CGM.getContext().getObjCEncodingForMethodDecl(I);
2036
0
    ClassMethodTypes.push_back(MakeConstantString(TypeStr));
2037
0
  }
2038
1
2039
1
  // Collect the names of referenced protocols
2040
1
  SmallVector<std::string, 16> Protocols;
2041
1
  const ObjCCategoryDecl *CatDecl = OCD->getCategoryDecl();
2042
1
  const ObjCList<ObjCProtocolDecl> &Protos = CatDecl->getReferencedProtocols();
2043
1
  for (ObjCList<ObjCProtocolDecl>::iterator I = Protos.begin(),
2044
1
       E = Protos.end(); 
I != E1
;
++I0
)
2045
0
    Protocols.push_back((*I)->getNameAsString());
2046
1
2047
1
  ConstantInitBuilder Builder(CGM);
2048
1
  auto Elements = Builder.beginStruct();
2049
1
  Elements.add(MakeConstantString(CategoryName));
2050
1
  Elements.add(MakeConstantString(ClassName));
2051
1
  // Instance method list
2052
1
  Elements.addBitCast(
2053
1
          GenerateMethodList(ClassName, CategoryName, InstanceMethodSels,
2054
1
                             InstanceMethodTypes, false),
2055
1
          PtrTy);
2056
1
  // Class method list
2057
1
  Elements.addBitCast(
2058
1
          GenerateMethodList(ClassName, CategoryName, ClassMethodSels,
2059
1
                             ClassMethodTypes, true),
2060
1
          PtrTy);
2061
1
  // Protocol list
2062
1
  Elements.addBitCast(GenerateProtocolList(Protocols), PtrTy);
2063
1
  Categories.push_back(llvm::ConstantExpr::getBitCast(
2064
1
        Elements.finishAndCreateGlobal("", CGM.getPointerAlign()),
2065
1
        PtrTy));
2066
1
}
2067
2068
llvm::Constant *CGObjCGNU::GeneratePropertyList(const ObjCImplementationDecl *OID,
2069
        SmallVectorImpl<Selector> &InstanceMethodSels,
2070
16
        SmallVectorImpl<llvm::Constant*> &InstanceMethodTypes) {
2071
16
  ASTContext &Context = CGM.getContext();
2072
16
  // Property metadata: name, attributes, attributes2, padding1, padding2,
2073
16
  // setter name, setter types, getter name, getter types.
2074
16
  llvm::StructType *propertyMetadataTy =
2075
16
    llvm::StructType::get(CGM.getLLVMContext(),
2076
16
        { PtrToInt8Ty, Int8Ty, Int8Ty, Int8Ty, Int8Ty, PtrToInt8Ty,
2077
16
          PtrToInt8Ty, PtrToInt8Ty, PtrToInt8Ty });
2078
16
2079
16
  unsigned numProperties = 0;
2080
12
  for (auto *propertyImpl : OID->property_impls()) {
2081
12
    (void) propertyImpl;
2082
12
    numProperties++;
2083
12
  }
2084
16
2085
16
  ConstantInitBuilder builder(CGM);
2086
16
  auto propertyList = builder.beginStruct();
2087
16
  propertyList.addInt(IntTy, numProperties);
2088
16
  propertyList.add(NULLPtr);
2089
16
  auto properties = propertyList.beginArray(propertyMetadataTy);
2090
16
2091
16
  // Add all of the property methods need adding to the method list and to the
2092
16
  // property metadata list.
2093
12
  for (auto *propertyImpl : OID->property_impls()) {
2094
12
    auto fields = properties.beginStruct(propertyMetadataTy);
2095
12
    ObjCPropertyDecl *property = propertyImpl->getPropertyDecl();
2096
12
    bool isSynthesized = (propertyImpl->getPropertyImplementation() == 
2097
12
        ObjCPropertyImplDecl::Synthesize);
2098
12
    bool isDynamic = (propertyImpl->getPropertyImplementation() == 
2099
12
        ObjCPropertyImplDecl::Dynamic);
2100
12
2101
12
    fields.add(MakePropertyEncodingString(property, OID));
2102
12
    PushPropertyAttributes(fields, property, isSynthesized, isDynamic);
2103
12
    if (ObjCMethodDecl *
getter12
= property->getGetterMethodDecl()) {
2104
12
      std::string TypeStr = Context.getObjCEncodingForMethodDecl(getter);
2105
12
      llvm::Constant *TypeEncoding = MakeConstantString(TypeStr);
2106
12
      if (
isSynthesized12
) {
2107
11
        InstanceMethodTypes.push_back(TypeEncoding);
2108
11
        InstanceMethodSels.push_back(getter->getSelector());
2109
11
      }
2110
12
      fields.add(MakeConstantString(getter->getSelector().getAsString()));
2111
12
      fields.add(TypeEncoding);
2112
0
    } else {
2113
0
      fields.add(NULLPtr);
2114
0
      fields.add(NULLPtr);
2115
0
    }
2116
12
    if (ObjCMethodDecl *
setter12
= property->getSetterMethodDecl()) {
2117
11
      std::string TypeStr = Context.getObjCEncodingForMethodDecl(setter);
2118
11
      llvm::Constant *TypeEncoding = MakeConstantString(TypeStr);
2119
11
      if (
isSynthesized11
) {
2120
11
        InstanceMethodTypes.push_back(TypeEncoding);
2121
11
        InstanceMethodSels.push_back(setter->getSelector());
2122
11
      }
2123
11
      fields.add(MakeConstantString(setter->getSelector().getAsString()));
2124
11
      fields.add(TypeEncoding);
2125
12
    } else {
2126
1
      fields.add(NULLPtr);
2127
1
      fields.add(NULLPtr);
2128
1
    }
2129
12
    fields.finishAndAddTo(properties);
2130
12
  }
2131
16
  properties.finishAndAddTo(propertyList);
2132
16
2133
16
  return propertyList.finishAndCreateGlobal(".objc_property_list",
2134
16
                                            CGM.getPointerAlign());
2135
16
}
2136
2137
0
void CGObjCGNU::RegisterAlias(const ObjCCompatibleAliasDecl *OAD) {
2138
0
  // Get the class declaration for which the alias is specified.
2139
0
  ObjCInterfaceDecl *ClassDecl =
2140
0
    const_cast<ObjCInterfaceDecl *>(OAD->getClassInterface());
2141
0
  ClassAliases.emplace_back(ClassDecl->getNameAsString(),
2142
0
                            OAD->getNameAsString());
2143
0
}
2144
2145
16
void CGObjCGNU::GenerateClass(const ObjCImplementationDecl *OID) {
2146
16
  ASTContext &Context = CGM.getContext();
2147
16
2148
16
  // Get the superclass name.
2149
16
  const ObjCInterfaceDecl * SuperClassDecl =
2150
16
    OID->getClassInterface()->getSuperClass();
2151
16
  std::string SuperClassName;
2152
16
  if (
SuperClassDecl16
) {
2153
7
    SuperClassName = SuperClassDecl->getNameAsString();
2154
7
    EmitClassRef(SuperClassName);
2155
7
  }
2156
16
2157
16
  // Get the class name
2158
16
  ObjCInterfaceDecl *ClassDecl =
2159
16
      const_cast<ObjCInterfaceDecl *>(OID->getClassInterface());
2160
16
  std::string ClassName = ClassDecl->getNameAsString();
2161
16
2162
16
  // Emit the symbol that is used to generate linker errors if this class is
2163
16
  // referenced in other modules but not declared.
2164
16
  std::string classSymbolName = "__objc_class_name_" + ClassName;
2165
16
  if (auto *
symbol16
= TheModule.getGlobalVariable(classSymbolName)) {
2166
0
    symbol->setInitializer(llvm::ConstantInt::get(LongTy, 0));
2167
16
  } else {
2168
16
    new llvm::GlobalVariable(TheModule, LongTy, false,
2169
16
                             llvm::GlobalValue::ExternalLinkage,
2170
16
                             llvm::ConstantInt::get(LongTy, 0),
2171
16
                             classSymbolName);
2172
16
  }
2173
16
2174
16
  // Get the size of instances.
2175
16
  int instanceSize = 
2176
16
    Context.getASTObjCImplementationLayout(OID).getSize().getQuantity();
2177
16
2178
16
  // Collect information about instance variables.
2179
16
  SmallVector<llvm::Constant*, 16> IvarNames;
2180
16
  SmallVector<llvm::Constant*, 16> IvarTypes;
2181
16
  SmallVector<llvm::Constant*, 16> IvarOffsets;
2182
16
2183
16
  ConstantInitBuilder IvarOffsetBuilder(CGM);
2184
16
  auto IvarOffsetValues = IvarOffsetBuilder.beginArray(PtrToIntTy);
2185
16
  SmallVector<bool, 16> WeakIvars;
2186
16
  SmallVector<bool, 16> StrongIvars;
2187
16
2188
9
  int superInstanceSize = !SuperClassDecl ? 0 :
2189
7
    Context.getASTObjCInterfaceLayout(SuperClassDecl).getSize().getQuantity();
2190
16
  // For non-fragile ivars, set the instance size to 0 - {the size of just this
2191
16
  // class}.  The runtime will then set this to the correct value on load.
2192
16
  if (
CGM.getLangOpts().ObjCRuntime.isNonFragile()16
) {
2193
9
    instanceSize = 0 - (instanceSize - superInstanceSize);
2194
9
  }
2195
16
2196
42
  for (const ObjCIvarDecl *IVD = ClassDecl->all_declared_ivar_begin(); IVD;
2197
26
       
IVD = IVD->getNextIvar()26
) {
2198
26
      // Store the name
2199
26
      IvarNames.push_back(MakeConstantString(IVD->getNameAsString()));
2200
26
      // Get the type encoding for this ivar
2201
26
      std::string TypeStr;
2202
26
      Context.getObjCEncodingForType(IVD->getType(), TypeStr, IVD);
2203
26
      IvarTypes.push_back(MakeConstantString(TypeStr));
2204
26
      // Get the offset
2205
26
      uint64_t BaseOffset = ComputeIvarBaseOffset(CGM, OID, IVD);
2206
26
      uint64_t Offset = BaseOffset;
2207
26
      if (
CGM.getLangOpts().ObjCRuntime.isNonFragile()26
) {
2208
15
        Offset = BaseOffset - superInstanceSize;
2209
15
      }
2210
26
      llvm::Constant *OffsetValue = llvm::ConstantInt::get(IntTy, Offset);
2211
26
      // Create the direct offset value
2212
26
      std::string OffsetName = "__objc_ivar_offset_value_" + ClassName +"." +
2213
26
          IVD->getNameAsString();
2214
26
      llvm::GlobalVariable *OffsetVar = TheModule.getGlobalVariable(OffsetName);
2215
26
      if (
OffsetVar26
) {
2216
2
        OffsetVar->setInitializer(OffsetValue);
2217
2
        // If this is the real definition, change its linkage type so that
2218
2
        // different modules will use this one, rather than their private
2219
2
        // copy.
2220
2
        OffsetVar->setLinkage(llvm::GlobalValue::ExternalLinkage);
2221
2
      } else
2222
24
        OffsetVar = new llvm::GlobalVariable(TheModule, IntTy,
2223
24
          false, llvm::GlobalValue::ExternalLinkage,
2224
24
          OffsetValue,
2225
24
          "__objc_ivar_offset_value_" + ClassName +"." +
2226
24
          IVD->getNameAsString());
2227
26
      IvarOffsets.push_back(OffsetValue);
2228
26
      IvarOffsetValues.add(OffsetVar);
2229
26
      Qualifiers::ObjCLifetime lt = IVD->getType().getQualifiers().getObjCLifetime();
2230
26
      switch (lt) {
2231
0
        case Qualifiers::OCL_Strong:
2232
0
          StrongIvars.push_back(true);
2233
0
          WeakIvars.push_back(false);
2234
0
          break;
2235
0
        case Qualifiers::OCL_Weak:
2236
0
          StrongIvars.push_back(false);
2237
0
          WeakIvars.push_back(true);
2238
0
          break;
2239
26
        default:
2240
26
          StrongIvars.push_back(false);
2241
26
          WeakIvars.push_back(false);
2242
26
      }
2243
26
  }
2244
16
  llvm::Constant *StrongIvarBitmap = MakeBitField(StrongIvars);
2245
16
  llvm::Constant *WeakIvarBitmap = MakeBitField(WeakIvars);
2246
16
  llvm::GlobalVariable *IvarOffsetArray =
2247
16
    IvarOffsetValues.finishAndCreateGlobal(".ivar.offsets",
2248
16
                                           CGM.getPointerAlign());
2249
16
2250
16
  // Collect information about instance methods
2251
16
  SmallVector<Selector, 16> InstanceMethodSels;
2252
16
  SmallVector<llvm::Constant*, 16> InstanceMethodTypes;
2253
5
  for (const auto *I : OID->instance_methods()) {
2254
5
    InstanceMethodSels.push_back(I->getSelector());
2255
5
    std::string TypeStr = Context.getObjCEncodingForMethodDecl(I);
2256
5
    InstanceMethodTypes.push_back(MakeConstantString(TypeStr));
2257
5
  }
2258
16
2259
16
  llvm::Constant *Properties = GeneratePropertyList(OID, InstanceMethodSels,
2260
16
          InstanceMethodTypes);
2261
16
2262
16
  // Collect information about class methods
2263
16
  SmallVector<Selector, 16> ClassMethodSels;
2264
16
  SmallVector<llvm::Constant*, 16> ClassMethodTypes;
2265
1
  for (const auto *I : OID->class_methods()) {
2266
1
    ClassMethodSels.push_back(I->getSelector());
2267
1
    std::string TypeStr = Context.getObjCEncodingForMethodDecl(I);
2268
1
    ClassMethodTypes.push_back(MakeConstantString(TypeStr));
2269
1
  }
2270
16
  // Collect the names of referenced protocols
2271
16
  SmallVector<std::string, 16> Protocols;
2272
16
  for (const auto *I : ClassDecl->protocols())
2273
2
    Protocols.push_back(I->getNameAsString());
2274
16
2275
16
  // Get the superclass pointer.
2276
16
  llvm::Constant *SuperClass;
2277
16
  if (
!SuperClassName.empty()16
) {
2278
7
    SuperClass = MakeConstantString(SuperClassName, ".super_class_name");
2279
16
  } else {
2280
9
    SuperClass = llvm::ConstantPointerNull::get(PtrToInt8Ty);
2281
9
  }
2282
16
  // Empty vector used to construct empty method lists
2283
16
  SmallVector<llvm::Constant*, 1>  empty;
2284
16
  // Generate the method and instance variable lists
2285
16
  llvm::Constant *MethodList = GenerateMethodList(ClassName, "",
2286
16
      InstanceMethodSels, InstanceMethodTypes, false);
2287
16
  llvm::Constant *ClassMethodList = GenerateMethodList(ClassName, "",
2288
16
      ClassMethodSels, ClassMethodTypes, true);
2289
16
  llvm::Constant *IvarList = GenerateIvarList(IvarNames, IvarTypes,
2290
16
      IvarOffsets);
2291
16
  // Irrespective of whether we are compiling for a fragile or non-fragile ABI,
2292
16
  // we emit a symbol containing the offset for each ivar in the class.  This
2293
16
  // allows code compiled for the non-Fragile ABI to inherit from code compiled
2294
16
  // for the legacy ABI, without causing problems.  The converse is also
2295
16
  // possible, but causes all ivar accesses to be fragile.
2296
16
2297
16
  // Offset pointer for getting at the correct field in the ivar list when
2298
16
  // setting up the alias.  These are: The base address for the global, the
2299
16
  // ivar array (second field), the ivar in this list (set for each ivar), and
2300
16
  // the offset (third field in ivar structure)
2301
16
  llvm::Type *IndexTy = Int32Ty;
2302
16
  llvm::Constant *offsetPointerIndexes[] = {Zeros[0],
2303
16
      llvm::ConstantInt::get(IndexTy, 1), nullptr,
2304
16
      llvm::ConstantInt::get(IndexTy, 2) };
2305
16
2306
16
  unsigned ivarIndex = 0;
2307
42
  for (const ObjCIvarDecl *IVD = ClassDecl->all_declared_ivar_begin(); IVD;
2308
26
       
IVD = IVD->getNextIvar()26
) {
2309
26
      const std::string Name = "__objc_ivar_offset_" + ClassName + '.'
2310
26
          + IVD->getNameAsString();
2311
26
      offsetPointerIndexes[2] = llvm::ConstantInt::get(IndexTy, ivarIndex);
2312
26
      // Get the correct ivar field
2313
26
      llvm::Constant *offsetValue = llvm::ConstantExpr::getGetElementPtr(
2314
26
          cast<llvm::GlobalVariable>(IvarList)->getValueType(), IvarList,
2315
26
          offsetPointerIndexes);
2316
26
      // Get the existing variable, if one exists.
2317
26
      llvm::GlobalVariable *offset = TheModule.getNamedGlobal(Name);
2318
26
      if (
offset26
) {
2319
10
        offset->setInitializer(offsetValue);
2320
10
        // If this is the real definition, change its linkage type so that
2321
10
        // different modules will use this one, rather than their private
2322
10
        // copy.
2323
10
        offset->setLinkage(llvm::GlobalValue::ExternalLinkage);
2324
26
      } else {
2325
16
        // Add a new alias if there isn't one already.
2326
16
        offset = new llvm::GlobalVariable(TheModule, offsetValue->getType(),
2327
16
                false, llvm::GlobalValue::ExternalLinkage, offsetValue, Name);
2328
16
        (void) offset; // Silence dead store warning.
2329
16
      }
2330
26
      ++ivarIndex;
2331
26
  }
2332
16
  llvm::Constant *ZeroPtr = llvm::ConstantInt::get(IntPtrTy, 0);
2333
16
2334
16
  //Generate metaclass for class methods
2335
16
  llvm::Constant *MetaClassStruct = GenerateClassStructure(
2336
16
      NULLPtr, NULLPtr, 0x12L, ClassName.c_str(), nullptr, Zeros[0],
2337
16
      GenerateIvarList(empty, empty, empty), ClassMethodList, NULLPtr, NULLPtr,
2338
16
      NULLPtr, ZeroPtr, ZeroPtr, true);
2339
16
  if (
CGM.getTriple().isOSBinFormatCOFF()16
) {
2340
5
    auto Storage = llvm::GlobalValue::DefaultStorageClass;
2341
5
    if (OID->getClassInterface()->hasAttr<DLLImportAttr>())
2342
0
      Storage = llvm::GlobalValue::DLLImportStorageClass;
2343
5
    else 
if (5
OID->getClassInterface()->hasAttr<DLLExportAttr>()5
)
2344
3
      Storage = llvm::GlobalValue::DLLExportStorageClass;
2345
5
    cast<llvm::GlobalValue>(MetaClassStruct)->setDLLStorageClass(Storage);
2346
5
  }
2347
16
2348
16
  // Generate the class structure
2349
16
  llvm::Constant *ClassStruct = GenerateClassStructure(
2350
16
      MetaClassStruct, SuperClass, 0x11L, ClassName.c_str(), nullptr,
2351
16
      llvm::ConstantInt::get(LongTy, instanceSize), IvarList, MethodList,
2352
16
      GenerateProtocolList(Protocols), IvarOffsetArray, Properties,
2353
16
      StrongIvarBitmap, WeakIvarBitmap);
2354
16
  if (
CGM.getTriple().isOSBinFormatCOFF()16
) {
2355
5
    auto Storage = llvm::GlobalValue::DefaultStorageClass;
2356
5
    if (OID->getClassInterface()->hasAttr<DLLImportAttr>())
2357
0
      Storage = llvm::GlobalValue::DLLImportStorageClass;
2358
5
    else 
if (5
OID->getClassInterface()->hasAttr<DLLExportAttr>()5
)
2359
3
      Storage = llvm::GlobalValue::DLLExportStorageClass;
2360
5
    cast<llvm::GlobalValue>(ClassStruct)->setDLLStorageClass(Storage);
2361
5
  }
2362
16
2363
16
  // Resolve the class aliases, if they exist.
2364
16
  if (
ClassPtrAlias16
) {
2365
1
    ClassPtrAlias->replaceAllUsesWith(
2366
1
        llvm::ConstantExpr::getBitCast(ClassStruct, IdTy));
2367
1
    ClassPtrAlias->eraseFromParent();
2368
1
    ClassPtrAlias = nullptr;
2369
1
  }
2370
16
  if (
MetaClassPtrAlias16
) {
2371
1
    MetaClassPtrAlias->replaceAllUsesWith(
2372
1
        llvm::ConstantExpr::getBitCast(MetaClassStruct, IdTy));
2373
1
    MetaClassPtrAlias->eraseFromParent();
2374
1
    MetaClassPtrAlias = nullptr;
2375
1
  }
2376
16
2377
16
  // Add class structure to list to be added to the symtab later
2378
16
  ClassStruct = llvm::ConstantExpr::getBitCast(ClassStruct, PtrToInt8Ty);
2379
16
  Classes.push_back(ClassStruct);
2380
16
}
2381
2382
23
llvm::Function *CGObjCGNU::ModuleInitFunction() {
2383
23
  // Only emit an ObjC load function if no Objective-C stuff has been called
2384
23
  if (
Classes.empty() && 23
Categories.empty()12
&&
ConstantStrings.empty()12
&&
2385
23
      
ExistingProtocols.empty()10
&&
SelectorTable.empty()10
)
2386
5
    return nullptr;
2387
18
2388
18
  // Add all referenced protocols to a category.
2389
18
  GenerateProtocolHolderCategory();
2390
18
2391
18
  llvm::StructType *selStructTy =
2392
18
    dyn_cast<llvm::StructType>(SelectorTy->getElementType());
2393
18
  llvm::Type *selStructPtrTy = SelectorTy;
2394
18
  if (
!selStructTy18
) {
2395
18
    selStructTy = llvm::StructType::get(CGM.getLLVMContext(),
2396
18
                                        { PtrToInt8Ty, PtrToInt8Ty });
2397
18
    selStructPtrTy = llvm::PointerType::getUnqual(selStructTy);
2398
18
  }
2399
18
2400
18
  // Generate statics list:
2401
18
  llvm::Constant *statics = NULLPtr;
2402
18
  if (
!ConstantStrings.empty()18
) {
2403
3
    llvm::GlobalVariable *fileStatics = [&] {
2404
3
      ConstantInitBuilder builder(CGM);
2405
3
      auto staticsStruct = builder.beginStruct();
2406
3
2407
3
      StringRef stringClass = CGM.getLangOpts().ObjCConstantStringClass;
2408
3
      if (
stringClass.empty()3
)
stringClass = "NXConstantString"2
;
2409
3
      staticsStruct.add(MakeConstantString(stringClass,
2410
3
                                           ".objc_static_class_name"));
2411
3
2412
3
      auto array = staticsStruct.beginArray();
2413
3
      array.addAll(ConstantStrings);
2414
3
      array.add(NULLPtr);
2415
3
      array.finishAndAddTo(staticsStruct);
2416
3
2417
3
      return staticsStruct.finishAndCreateGlobal(".objc_statics",
2418
3
                                                 CGM.getPointerAlign());
2419
3
    }();
2420
3
2421
3
    ConstantInitBuilder builder(CGM);
2422
3
    auto allStaticsArray = builder.beginArray(fileStatics->getType());
2423
3
    allStaticsArray.add(fileStatics);
2424
3
    allStaticsArray.addNullPointer(fileStatics->getType());
2425
3
2426
3
    statics = allStaticsArray.finishAndCreateGlobal(".objc_statics_ptr",
2427
3
                                                    CGM.getPointerAlign());
2428
3
    statics = llvm::ConstantExpr::getBitCast(statics, PtrTy);
2429
3
  }
2430
18
2431
18
  // Array of classes, categories, and constant objects.
2432
18
2433
18
  SmallVector<llvm::GlobalAlias*, 16> selectorAliases;
2434
18
  unsigned selectorCount;
2435
18
2436
18
  // Pointer to an array of selectors used in this module.
2437
18
  llvm::GlobalVariable *selectorList = [&] {
2438
18
    ConstantInitBuilder builder(CGM);
2439
18
    auto selectors = builder.beginArray(selStructTy);
2440
18
    auto &table = SelectorTable; // MSVC workaround
2441
19
    for (auto &entry : table) {
2442
19
2443
19
      std::string selNameStr = entry.first.getAsString();
2444
19
      llvm::Constant *selName = ExportUniqueString(selNameStr, ".objc_sel_name");
2445
19
2446
19
      for (TypedSelector &sel : entry.second) {
2447
19
        llvm::Constant *selectorTypeEncoding = NULLPtr;
2448
19
        if (!sel.first.empty())
2449
5
          selectorTypeEncoding =
2450
5
            MakeConstantString(sel.first, ".objc_sel_types");
2451
19
2452
19
        auto selStruct = selectors.beginStruct(selStructTy);
2453
19
        selStruct.add(selName);
2454
19
        selStruct.add(selectorTypeEncoding);
2455
19
        selStruct.finishAndAddTo(selectors);
2456
19
2457
19
        // Store the selector alias for later replacement
2458
19
        selectorAliases.push_back(sel.second);
2459
19
      }
2460
19
    }
2461
18
2462
18
    // Remember the number of entries in the selector table.
2463
18
    selectorCount = selectors.size();
2464
18
2465
18
    // NULL-terminate the selector list.  This should not actually be required,
2466
18
    // because the selector list has a length field.  Unfortunately, the GCC
2467
18
    // runtime decides to ignore the length field and expects a NULL terminator,
2468
18
    // and GCC cooperates with this by always setting the length to 0.
2469
18
    auto selStruct = selectors.beginStruct(selStructTy);
2470
18
    selStruct.add(NULLPtr);
2471
18
    selStruct.add(NULLPtr);
2472
18
    selStruct.finishAndAddTo(selectors);
2473
18
2474
18
    return selectors.finishAndCreateGlobal(".objc_selector_list",
2475
18
                                           CGM.getPointerAlign());
2476
18
  }();
2477
18
2478
18
  // Now that all of the static selectors exist, create pointers to them.
2479
37
  for (unsigned i = 0; 
i < selectorCount37
;
++i19
) {
2480
19
    llvm::Constant *idxs[] = {
2481
19
      Zeros[0],
2482
19
      llvm::ConstantInt::get(Int32Ty, i)
2483
19
    };
2484
19
    // FIXME: We're generating redundant loads and stores here!
2485
19
    llvm::Constant *selPtr = llvm::ConstantExpr::getGetElementPtr(
2486
19
        selectorList->getValueType(), selectorList, idxs);
2487
19
    // If selectors are defined as an opaque type, cast the pointer to this
2488
19
    // type.
2489
19
    selPtr = llvm::ConstantExpr::getBitCast(selPtr, SelectorTy);
2490
19
    selectorAliases[i]->replaceAllUsesWith(selPtr);
2491
19
    selectorAliases[i]->eraseFromParent();
2492
19
  }
2493
18
2494
18
  llvm::GlobalVariable *symtab = [&] {
2495
18
    ConstantInitBuilder builder(CGM);
2496
18
    auto symtab = builder.beginStruct();
2497
18
2498
18
    // Number of static selectors
2499
18
    symtab.addInt(LongTy, selectorCount);
2500
18
2501
18
    symtab.addBitCast(selectorList, selStructPtrTy);
2502
18
2503
18
    // Number of classes defined.
2504
18
    symtab.addInt(CGM.Int16Ty, Classes.size());
2505
18
    // Number of categories defined
2506
18
    symtab.addInt(CGM.Int16Ty, Categories.size());
2507
18
2508
18
    // Create an array of classes, then categories, then static object instances
2509
18
    auto classList = symtab.beginArray(PtrToInt8Ty);
2510
18
    classList.addAll(Classes);
2511
18
    classList.addAll(Categories);
2512
18
    //  NULL-terminated list of static object instances (mainly constant strings)
2513
18
    classList.add(statics);
2514
18
    classList.add(NULLPtr);
2515
18
    classList.finishAndAddTo(symtab);
2516
18
2517
18
    // Construct the symbol table.
2518
18
    return symtab.finishAndCreateGlobal("", CGM.getPointerAlign());
2519
18
  }();
2520
18
2521
18
  // The symbol table is contained in a module which has some version-checking
2522
18
  // constants
2523
18
  llvm::Constant *module = [&] {
2524
18
    llvm::Type *moduleEltTys[] = {
2525
18
      LongTy, LongTy, PtrToInt8Ty, symtab->getType(), IntTy
2526
18
    };
2527
18
    llvm::StructType *moduleTy =
2528
18
      llvm::StructType::get(CGM.getLLVMContext(),
2529
18
         makeArrayRef(moduleEltTys).drop_back(unsigned(RuntimeVersion < 10)));
2530
18
2531
18
    ConstantInitBuilder builder(CGM);
2532
18
    auto module = builder.beginStruct(moduleTy);
2533
18
    // Runtime version, used for ABI compatibility checking.
2534
18
    module.addInt(LongTy, RuntimeVersion);
2535
18
    // sizeof(ModuleTy)
2536
18
    module.addInt(LongTy, CGM.getDataLayout().getTypeStoreSize(moduleTy));
2537
18
2538
18
    // The path to the source file where this module was declared
2539
18
    SourceManager &SM = CGM.getContext().getSourceManager();
2540
18
    const FileEntry *mainFile = SM.getFileEntryForID(SM.getMainFileID());
2541
18
    std::string path =
2542
18
      (Twine(mainFile->getDir()->getName()) + "/" + mainFile->getName()).str();
2543
18
    module.add(MakeConstantString(path, ".objc_source_file_name"));
2544
18
    module.add(symtab);
2545
18
2546
18
    if (
RuntimeVersion >= 1018
) {
2547
1
      switch (CGM.getLangOpts().getGC()) {
2548
0
      case LangOptions::GCOnly:
2549
0
        module.addInt(IntTy, 2);
2550
0
        break;
2551
1
      case LangOptions::NonGC:
2552
1
        if (CGM.getLangOpts().ObjCAutoRefCount)
2553
1
          module.addInt(IntTy, 1);
2554
1
        else
2555
0
          module.addInt(IntTy, 0);
2556
1
        break;
2557
0
      case LangOptions::HybridGC:
2558
0
        module.addInt(IntTy, 1);
2559
0
        break;
2560
18
      }
2561
18
    }
2562
18
2563
18
    return module.finishAndCreateGlobal("", CGM.getPointerAlign());
2564
18
  }();
2565
18
2566
18
  // Create the load function calling the runtime entry point with the module
2567
18
  // structure
2568
18
  llvm::Function * LoadFunction = llvm::Function::Create(
2569
18
      llvm::FunctionType::get(llvm::Type::getVoidTy(VMContext), false),
2570
18
      llvm::GlobalValue::InternalLinkage, ".objc_load_function",
2571
18
      &TheModule);
2572
18
  llvm::BasicBlock *EntryBB =
2573
18
      llvm::BasicBlock::Create(VMContext, "entry", LoadFunction);
2574
18
  CGBuilderTy Builder(CGM, VMContext);
2575
18
  Builder.SetInsertPoint(EntryBB);
2576
18
2577
18
  llvm::FunctionType *FT =
2578
18
    llvm::FunctionType::get(Builder.getVoidTy(), module->getType(), true);
2579
18
  llvm::Value *Register = CGM.CreateRuntimeFunction(FT, "__objc_exec_class");
2580
18
  Builder.CreateCall(Register, module);
2581
18
2582
18
  if (
!ClassAliases.empty()18
) {
2583
0
    llvm::Type *ArgTypes[2] = {PtrTy, PtrToInt8Ty};
2584
0
    llvm::FunctionType *RegisterAliasTy =
2585
0
      llvm::FunctionType::get(Builder.getVoidTy(),
2586
0
                              ArgTypes, false);
2587
0
    llvm::Function *RegisterAlias = llvm::Function::Create(
2588
0
      RegisterAliasTy,
2589
0
      llvm::GlobalValue::ExternalWeakLinkage, "class_registerAlias_np",
2590
0
      &TheModule);
2591
0
    llvm::BasicBlock *AliasBB =
2592
0
      llvm::BasicBlock::Create(VMContext, "alias", LoadFunction);
2593
0
    llvm::BasicBlock *NoAliasBB =
2594
0
      llvm::BasicBlock::Create(VMContext, "no_alias", LoadFunction);
2595
0
2596
0
    // Branch based on whether the runtime provided class_registerAlias_np()
2597
0
    llvm::Value *HasRegisterAlias = Builder.CreateICmpNE(RegisterAlias,
2598
0
            llvm::Constant::getNullValue(RegisterAlias->getType()));
2599
0
    Builder.CreateCondBr(HasRegisterAlias, AliasBB, NoAliasBB);
2600
0
2601
0
    // The true branch (has alias registration function):
2602
0
    Builder.SetInsertPoint(AliasBB);
2603
0
    // Emit alias registration calls:
2604
0
    for (std::vector<ClassAliasPair>::iterator iter = ClassAliases.begin();
2605
0
       
iter != ClassAliases.end()0
;
++iter0
) {
2606
0
       llvm::Constant *TheClass =
2607
0
          TheModule.getGlobalVariable("_OBJC_CLASS_" + iter->first, true);
2608
0
       if (
TheClass0
) {
2609
0
         TheClass = llvm::ConstantExpr::getBitCast(TheClass, PtrTy);
2610
0
         Builder.CreateCall(RegisterAlias,
2611
0
                            {TheClass, MakeConstantString(iter->second)});
2612
0
       }
2613
0
    }
2614
0
    // Jump to end:
2615
0
    Builder.CreateBr(NoAliasBB);
2616
0
2617
0
    // Missing alias registration function, just return from the function:
2618
0
    Builder.SetInsertPoint(NoAliasBB);
2619
0
  }
2620
23
  Builder.CreateRetVoid();
2621
23
2622
23
  return LoadFunction;
2623
23
}
2624
2625
llvm::Function *CGObjCGNU::GenerateMethod(const ObjCMethodDecl *OMD,
2626
28
                                          const ObjCContainerDecl *CD) {
2627
28
  const ObjCCategoryImplDecl *OCD =
2628
28
    dyn_cast<ObjCCategoryImplDecl>(OMD->getDeclContext());
2629
28
  StringRef CategoryName = OCD ? 
OCD->getName()0
:
""28
;
2630
28
  StringRef ClassName = CD->getName();
2631
28
  Selector MethodName = OMD->getSelector();
2632
28
  bool isClassMethod = !OMD->isInstanceMethod();
2633
28
2634
28
  CodeGenTypes &Types = CGM.getTypes();
2635
28
  llvm::FunctionType *MethodTy =
2636
28
    Types.GetFunctionType(Types.arrangeObjCMethodDeclaration(OMD));
2637
28
  std::string FunctionName = SymbolNameForMethod(ClassName, CategoryName,
2638
28
      MethodName, isClassMethod);
2639
28
2640
28
  llvm::Function *Method
2641
28
    = llvm::Function::Create(MethodTy,
2642
28
                             llvm::GlobalValue::InternalLinkage,
2643
28
                             FunctionName,
2644
28
                             &TheModule);
2645
28
  return Method;
2646
28
}
2647
2648
3
llvm::Constant *CGObjCGNU::GetPropertyGetFunction() {
2649
3
  return GetPropertyFn;
2650
3
}
2651
2652
0
llvm::Constant *CGObjCGNU::GetPropertySetFunction() {
2653
0
  return SetPropertyFn;
2654
0
}
2655
2656
llvm::Constant *CGObjCGNU::GetOptimizedPropertySetFunction(bool atomic,
2657
0
                                                           bool copy) {
2658
0
  return nullptr;
2659
0
}
2660
2661
0
llvm::Constant *CGObjCGNU::GetGetStructFunction() {
2662
0
  return GetStructPropertyFn;
2663
0
}
2664
2665
0
llvm::Constant *CGObjCGNU::GetSetStructFunction() {
2666
0
  return SetStructPropertyFn;
2667
0
}
2668
2669
0
llvm::Constant *CGObjCGNU::GetCppAtomicObjectGetFunction() {
2670
0
  return nullptr;
2671
0
}
2672
2673
0
llvm::Constant *CGObjCGNU::GetCppAtomicObjectSetFunction() {
2674
0
  return nullptr;
2675
0
}
2676
2677
1
llvm::Constant *CGObjCGNU::EnumerationMutationFunction() {
2678
1
  return EnumerationMutationFn;
2679
1
}
2680
2681
void CGObjCGNU::EmitSynchronizedStmt(CodeGenFunction &CGF,
2682
1
                                     const ObjCAtSynchronizedStmt &S) {
2683
1
  EmitAtSynchronizedStmt(CGF, S, SyncEnterFn, SyncExitFn);
2684
1
}
2685
2686
2687
void CGObjCGNU::EmitTryStmt(CodeGenFunction &CGF,
2688
4
                            const ObjCAtTryStmt &S) {
2689
4
  // Unlike the Apple non-fragile runtimes, which also uses
2690
4
  // unwind-based zero cost exceptions, the GNU Objective C runtime's
2691
4
  // EH support isn't a veneer over C++ EH.  Instead, exception
2692
4
  // objects are created by objc_exception_throw and destroyed by
2693
4
  // the personality function; this avoids the need for bracketing
2694
4
  // catch handlers with calls to __blah_begin_catch/__blah_end_catch
2695
4
  // (or even _Unwind_DeleteException), but probably doesn't
2696
4
  // interoperate very well with foreign exceptions.
2697
4
  //
2698
4
  // In Objective-C++ mode, we actually emit something equivalent to the C++
2699
4
  // exception handler. 
2700
4
  EmitTryCatchStmt(CGF, S, EnterCatchFn, ExitCatchFn, ExceptionReThrowFn);
2701
4
}
2702
2703
void CGObjCGNU::EmitThrowStmt(CodeGenFunction &CGF,
2704
                              const ObjCAtThrowStmt &S,
2705
3
                              bool ClearInsertionPoint) {
2706
3
  llvm::Value *ExceptionAsObject;
2707
3
2708
3
  if (const Expr *
ThrowExpr3
= S.getThrowExpr()) {
2709
2
    llvm::Value *Exception = CGF.EmitObjCThrowOperand(ThrowExpr);
2710
2
    ExceptionAsObject = Exception;
2711
3
  } else {
2712
1
    assert((!CGF.ObjCEHValueStack.empty() && CGF.ObjCEHValueStack.back()) &&
2713
1
           "Unexpected rethrow outside @catch block.");
2714
1
    ExceptionAsObject = CGF.ObjCEHValueStack.back();
2715
1
  }
2716
3
  ExceptionAsObject = CGF.Builder.CreateBitCast(ExceptionAsObject, IdTy);
2717
3
  llvm::CallSite Throw =
2718
3
      CGF.EmitRuntimeCallOrInvoke(ExceptionThrowFn, ExceptionAsObject);
2719
3
  Throw.setDoesNotReturn();
2720
3
  CGF.Builder.CreateUnreachable();
2721
3
  if (ClearInsertionPoint)
2722
3
    CGF.Builder.ClearInsertionPoint();
2723
3
}
2724
2725
llvm::Value * CGObjCGNU::EmitObjCWeakRead(CodeGenFunction &CGF,
2726
0
                                          Address AddrWeakObj) {
2727
0
  CGBuilderTy &B = CGF.Builder;
2728
0
  AddrWeakObj = EnforceType(B, AddrWeakObj, PtrToIdTy);
2729
0
  return B.CreateCall(WeakReadFn.getType(), WeakReadFn,
2730
0
                      AddrWeakObj.getPointer());
2731
0
}
2732
2733
void CGObjCGNU::EmitObjCWeakAssign(CodeGenFunction &CGF,
2734
0
                                   llvm::Value *src, Address dst) {
2735
0
  CGBuilderTy &B = CGF.Builder;
2736
0
  src = EnforceType(B, src, IdTy);
2737
0
  dst = EnforceType(B, dst, PtrToIdTy);
2738
0
  B.CreateCall(WeakAssignFn.getType(), WeakAssignFn,
2739
0
               {src, dst.getPointer()});
2740
0
}
2741
2742
void CGObjCGNU::EmitObjCGlobalAssign(CodeGenFunction &CGF,
2743
                                     llvm::Value *src, Address dst,
2744
0
                                     bool threadlocal) {
2745
0
  CGBuilderTy &B = CGF.Builder;
2746
0
  src = EnforceType(B, src, IdTy);
2747
0
  dst = EnforceType(B, dst, PtrToIdTy);
2748
0
  // FIXME. Add threadloca assign API
2749
0
  assert(!threadlocal && "EmitObjCGlobalAssign - Threal Local API NYI");
2750
0
  B.CreateCall(GlobalAssignFn.getType(), GlobalAssignFn,
2751
0
               {src, dst.getPointer()});
2752
0
}
2753
2754
void CGObjCGNU::EmitObjCIvarAssign(CodeGenFunction &CGF,
2755
                                   llvm::Value *src, Address dst,
2756
0
                                   llvm::Value *ivarOffset) {
2757
0
  CGBuilderTy &B = CGF.Builder;
2758
0
  src = EnforceType(B, src, IdTy);
2759
0
  dst = EnforceType(B, dst, IdTy);
2760
0
  B.CreateCall(IvarAssignFn.getType(), IvarAssignFn,
2761
0
               {src, dst.getPointer(), ivarOffset});
2762
0
}
2763
2764
void CGObjCGNU::EmitObjCStrongCastAssign(CodeGenFunction &CGF,
2765
0
                                         llvm::Value *src, Address dst) {
2766
0
  CGBuilderTy &B = CGF.Builder;
2767
0
  src = EnforceType(B, src, IdTy);
2768
0
  dst = EnforceType(B, dst, PtrToIdTy);
2769
0
  B.CreateCall(StrongCastAssignFn.getType(), StrongCastAssignFn,
2770
0
               {src, dst.getPointer()});
2771
0
}
2772
2773
void CGObjCGNU::EmitGCMemmoveCollectable(CodeGenFunction &CGF,
2774
                                         Address DestPtr,
2775
                                         Address SrcPtr,
2776
0
                                         llvm::Value *Size) {
2777
0
  CGBuilderTy &B = CGF.Builder;
2778
0
  DestPtr = EnforceType(B, DestPtr, PtrTy);
2779
0
  SrcPtr = EnforceType(B, SrcPtr, PtrTy);
2780
0
2781
0
  B.CreateCall(MemMoveFn.getType(), MemMoveFn,
2782
0
               {DestPtr.getPointer(), SrcPtr.getPointer(), Size});
2783
0
}
2784
2785
llvm::GlobalVariable *CGObjCGNU::ObjCIvarOffsetVariable(
2786
                              const ObjCInterfaceDecl *ID,
2787
21
                              const ObjCIvarDecl *Ivar) {
2788
21
  const std::string Name = "__objc_ivar_offset_" + ID->getNameAsString()
2789
21
    + '.' + Ivar->getNameAsString();
2790
21
  // Emit the variable and initialize it with what we think the correct value
2791
21
  // is.  This allows code compiled with non-fragile ivars to work correctly
2792
21
  // when linked against code which isn't (most of the time).
2793
21
  llvm::GlobalVariable *IvarOffsetPointer = TheModule.getNamedGlobal(Name);
2794
21
  if (
!IvarOffsetPointer21
) {
2795
9
    // This will cause a run-time crash if we accidentally use it.  A value of
2796
9
    // 0 would seem more sensible, but will silently overwrite the isa pointer
2797
9
    // causing a great deal of confusion.
2798
9
    uint64_t Offset = -1;
2799
9
    // We can't call ComputeIvarBaseOffset() here if we have the
2800
9
    // implementation, because it will create an invalid ASTRecordLayout object
2801
9
    // that we are then stuck with forever, so we only initialize the ivar
2802
9
    // offset variable with a guess if we only have the interface.  The
2803
9
    // initializer will be reset later anyway, when we are generating the class
2804
9
    // description.
2805
9
    if (!CGM.getContext().getObjCImplementation(
2806
9
              const_cast<ObjCInterfaceDecl *>(ID)))
2807
1
      Offset = ComputeIvarBaseOffset(CGM, ID, Ivar);
2808
9
2809
9
    llvm::ConstantInt *OffsetGuess = llvm::ConstantInt::get(Int32Ty, Offset,
2810
9
                             /*isSigned*/true);
2811
9
    // Don't emit the guess in non-PIC code because the linker will not be able
2812
9
    // to replace it with the real version for a library.  In non-PIC code you
2813
9
    // must compile with the fragile ABI if you want to use ivars from a
2814
9
    // GCC-compiled class.
2815
9
    if (
CGM.getLangOpts().PICLevel9
) {
2816
2
      llvm::GlobalVariable *IvarOffsetGV = new llvm::GlobalVariable(TheModule,
2817
2
            Int32Ty, false,
2818
2
            llvm::GlobalValue::PrivateLinkage, OffsetGuess, Name+".guess");
2819
2
      IvarOffsetPointer = new llvm::GlobalVariable(TheModule,
2820
2
            IvarOffsetGV->getType(), false, llvm::GlobalValue::LinkOnceAnyLinkage,
2821
2
            IvarOffsetGV, Name);
2822
9
    } else {
2823
7
      IvarOffsetPointer = new llvm::GlobalVariable(TheModule,
2824
7
              llvm::Type::getInt32PtrTy(VMContext), false,
2825
7
              llvm::GlobalValue::ExternalLinkage, nullptr, Name);
2826
7
    }
2827
9
  }
2828
21
  return IvarOffsetPointer;
2829
21
}
2830
2831
LValue CGObjCGNU::EmitObjCValueForIvar(CodeGenFunction &CGF,
2832
                                       QualType ObjectTy,
2833
                                       llvm::Value *BaseValue,
2834
                                       const ObjCIvarDecl *Ivar,
2835
20
                                       unsigned CVRQualifiers) {
2836
20
  const ObjCInterfaceDecl *ID =
2837
20
    ObjectTy->getAs<ObjCObjectType>()->getInterface();
2838
20
  return EmitValueForIvarAtOffset(CGF, ID, BaseValue, Ivar, CVRQualifiers,
2839
20
                                  EmitIvarOffset(CGF, ID, Ivar));
2840
20
}
2841
2842
static const ObjCInterfaceDecl *FindIvarInterface(ASTContext &Context,
2843
                                                  const ObjCInterfaceDecl *OID,
2844
21
                                                  const ObjCIvarDecl *OIVD) {
2845
37
  for (const ObjCIvarDecl *next = OID->all_declared_ivar_begin(); next;
2846
21
       
next = next->getNextIvar()16
) {
2847
37
    if (OIVD == next)
2848
21
      return OID;
2849
37
  }
2850
21
2851
21
  // Otherwise check in the super class.
2852
0
  
if (const ObjCInterfaceDecl *0
Super0
= OID->getSuperClass())
2853
0
    return FindIvarInterface(Context, Super, OIVD);
2854
0
2855
0
  return nullptr;
2856
0
}
2857
2858
llvm::Value *CGObjCGNU::EmitIvarOffset(CodeGenFunction &CGF,
2859
                         const ObjCInterfaceDecl *Interface,
2860
27
                         const ObjCIvarDecl *Ivar) {
2861
27
  if (
CGM.getLangOpts().ObjCRuntime.isNonFragile()27
) {
2862
21
    Interface = FindIvarInterface(CGM.getContext(), Interface, Ivar);
2863
21
2864
21
    // The MSVC linker cannot have a single global defined as LinkOnceAnyLinkage
2865
21
    // and ExternalLinkage, so create a reference to the ivar global and rely on
2866
21
    // the definition being created as part of GenerateClass.
2867
21
    if (RuntimeVersion < 10 ||
2868
0
        CGF.CGM.getTarget().getTriple().isKnownWindowsMSVCEnvironment())
2869
21
      return CGF.Builder.CreateZExtOrBitCast(
2870
21
          CGF.Builder.CreateAlignedLoad(
2871
21
              Int32Ty, CGF.Builder.CreateAlignedLoad(
2872
21
                           ObjCIvarOffsetVariable(Interface, Ivar),
2873
21
                           CGF.getPointerAlign(), "ivar"),
2874
21
              CharUnits::fromQuantity(4)),
2875
21
          PtrDiffTy);
2876
0
    std::string name = "__objc_ivar_offset_value_" +
2877
0
      Interface->getNameAsString() +"." + Ivar->getNameAsString();
2878
0
    CharUnits Align = CGM.getIntAlign();
2879
0
    llvm::Value *Offset = TheModule.getGlobalVariable(name);
2880
0
    if (
!Offset0
) {
2881
0
      auto GV = new llvm::GlobalVariable(TheModule, IntTy,
2882
0
          false, llvm::GlobalValue::LinkOnceAnyLinkage,
2883
0
          llvm::Constant::getNullValue(IntTy), name);
2884
0
      GV->setAlignment(Align.getQuantity());
2885
0
      Offset = GV;
2886
0
    }
2887
0
    Offset = CGF.Builder.CreateAlignedLoad(Offset, Align);
2888
0
    if (Offset->getType() != PtrDiffTy)
2889
0
      Offset = CGF.Builder.CreateZExtOrBitCast(Offset, PtrDiffTy);
2890
21
    return Offset;
2891
21
  }
2892
6
  uint64_t Offset = ComputeIvarBaseOffset(CGF.CGM, Interface, Ivar);
2893
6
  return llvm::ConstantInt::get(PtrDiffTy, Offset, /*isSigned*/true);
2894
6
}
2895
2896
CGObjCRuntime *
2897
23
clang::CodeGen::CreateGNUObjCRuntime(CodeGenModule &CGM) {
2898
23
  switch (CGM.getLangOpts().ObjCRuntime.getKind()) {
2899
7
  case ObjCRuntime::GNUstep:
2900
7
    return new CGObjCGNUstep(CGM);
2901
23
2902
11
  case ObjCRuntime::GCC:
2903
11
    return new CGObjCGCC(CGM);
2904
23
2905
5
  case ObjCRuntime::ObjFW:
2906
5
    return new CGObjCObjFW(CGM);
2907
23
2908
0
  case ObjCRuntime::FragileMacOSX:
2909
0
  case ObjCRuntime::MacOSX:
2910
0
  case ObjCRuntime::iOS:
2911
0
  case ObjCRuntime::WatchOS:
2912
0
    llvm_unreachable("these runtimes are not GNU runtimes");
2913
0
  }
2914
0
  
llvm_unreachable0
("bad runtime");
2915
0
}