forked from swiftlang/swift
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathGenObjC.cpp
1505 lines (1286 loc) · 57.7 KB
/
GenObjC.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//===--- GenObjC.cpp - Objective-C interaction ----------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
//
// This file implements bridging to Objective-C.
//
//===----------------------------------------------------------------------===//
#include "llvm/ADT/SmallString.h"
#include "llvm/ADT/StringExtras.h"
#include "llvm/IR/DerivedTypes.h"
#include "llvm/IR/Module.h"
#include "llvm/IR/InlineAsm.h"
#include "clang/AST/ASTContext.h"
#include "swift/AST/Attr.h"
#include "swift/AST/Decl.h"
#include "swift/AST/IRGenOptions.h"
#include "swift/ClangImporter/ClangImporter.h"
#include "swift/AST/Types.h"
#include "swift/SIL/SILModule.h"
#include "clang/AST/Attr.h"
#include "clang/AST/DeclObjC.h"
#include "CallEmission.h"
#include "Explosion.h"
#include "GenClass.h"
#include "GenFunc.h"
#include "GenHeap.h"
#include "GenMeta.h"
#include "GenProto.h"
#include "GenType.h"
#include "HeapTypeInfo.h"
#include "IRGenFunction.h"
#include "IRGenModule.h"
#include "Linking.h"
#include "ScalarTypeInfo.h"
#include "StructLayout.h"
#include "GenObjC.h"
using namespace swift;
using namespace irgen;
void IRGenFunction::emitObjCRelease(llvm::Value *value) {
// Get an appropriately-cast function pointer.
auto fn = IGM.getObjCReleaseFn();
if (value->getType() != IGM.ObjCPtrTy) {
auto fnTy = llvm::FunctionType::get(IGM.VoidTy, value->getType(),
false)->getPointerTo();
fn = llvm::ConstantExpr::getBitCast(fn, fnTy);
}
auto call = Builder.CreateCall(fn, value);
call->setDoesNotThrow();
}
/// Given a function of type %objc* (%objc*)*, cast it as appropriate
/// to be used with values of type T.
static llvm::Constant *getCastOfRetainFn(IRGenModule &IGM,
llvm::Constant *fn,
llvm::Type *valueTy) {
#ifndef NDEBUG
auto origFnTy = cast<llvm::FunctionType>(fn->getType()->getPointerElementType());
assert(origFnTy->getReturnType() == IGM.ObjCPtrTy);
assert(origFnTy->getNumParams() == 1);
assert(origFnTy->getParamType(0) == IGM.ObjCPtrTy);
assert(isa<llvm::PointerType>(valueTy) ||
valueTy == IGM.IntPtrTy); // happens with optional types
#endif
if (valueTy == IGM.ObjCPtrTy)
return fn;
auto fnTy = llvm::FunctionType::get(valueTy, valueTy, false);
return llvm::ConstantExpr::getBitCast(fn, fnTy->getPointerTo(0));
}
void IRGenFunction::emitObjCRetain(llvm::Value *v, Explosion &explosion) {
explosion.add(emitObjCRetainCall(v));
}
llvm::Value *IRGenFunction::emitObjCRetainCall(llvm::Value *value) {
// Get an appropriately cast function pointer.
auto fn = IGM.getObjCRetainFn();
fn = getCastOfRetainFn(IGM, fn, value->getType());
auto call = Builder.CreateCall(fn, value);
call->setDoesNotThrow();
return call;
}
llvm::Value *IRGenFunction::emitObjCAutoreleaseCall(llvm::Value *val) {
if (val->getType()->isPointerTy())
val = Builder.CreateBitCast(val, IGM.ObjCPtrTy);
else
val = Builder.CreateIntToPtr(val, IGM.ObjCPtrTy);
auto call = Builder.CreateCall(IGM.getObjCAutoreleaseFn(), val);
call->setDoesNotThrow();
return call;
}
llvm::Value *IRGenModule::getObjCRetainAutoreleasedReturnValueMarker() {
// Check to see if we've already computed the market. Note that we
// might have cached a null marker, and that's fine.
auto &cache = ObjCRetainAutoreleasedReturnValueMarker;
if (cache.hasValue())
return cache.getValue();
// Ask the target for the string.
StringRef asmString = TargetInfo.ObjCRetainAutoreleasedReturnValueMarker;
// If the string is empty, just leave, remembering that we did all this.
if (asmString.empty()) {
cache = nullptr;
return nullptr;
}
// If we're emitting optimized code, record the string in the module
// and let the late ARC pass insert it, but don't generate any calls
// right now.
if (Opts.Optimize) {
llvm::NamedMDNode *metadata =
Module.getOrInsertNamedMetadata(
"clang.arc.retainAutoreleasedReturnValueMarker");
assert(metadata->getNumOperands() <= 1);
if (metadata->getNumOperands() == 0) {
auto *string = llvm::MDString::get(LLVMContext, asmString);
metadata->addOperand(llvm::MDNode::get(LLVMContext, string));
}
cache = nullptr;
// Otherwise, create the module
} else {
llvm::FunctionType *type =
llvm::FunctionType::get(VoidTy, /*variadic*/false);
cache = llvm::InlineAsm::get(type, asmString, "", /*sideeffects*/ true);
}
return cache.getValue();
}
/// Reclaim an autoreleased return value.
llvm::Value *irgen::emitObjCRetainAutoreleasedReturnValue(IRGenFunction &IGF,
llvm::Value *value) {
// Call the inline-assembly marker if we need one.
if (auto marker = IGF.IGM.getObjCRetainAutoreleasedReturnValueMarker()) {
IGF.Builder.CreateCall(marker, {});
}
auto fn = IGF.IGM.getObjCRetainAutoreleasedReturnValueFn();
// We don't want to cast the function here because it interferes with
// LLVM's ability to recognize and special-case this function.
// Note that the parameter and result must also have type i8*.
llvm::Type *valueType = value->getType();
if (isa<llvm::PointerType>(valueType)) {
value = IGF.Builder.CreateBitCast(value, IGF.IGM.Int8PtrTy);
} else {
value = IGF.Builder.CreateIntToPtr(value, IGF.IGM.Int8PtrTy);
}
auto call = IGF.Builder.CreateCall(fn, value);
call->setDoesNotThrow();
llvm::Value *result = call;
if (isa<llvm::PointerType>(valueType)) {
result = IGF.Builder.CreateBitCast(result, valueType);
} else {
result = IGF.Builder.CreatePtrToInt(result, valueType);
}
return result;
}
/// Autorelease a return value.
llvm::Value *irgen::emitObjCAutoreleaseReturnValue(IRGenFunction &IGF,
llvm::Value *value) {
auto fn = IGF.IGM.getObjCAutoreleaseReturnValueFn();
fn = getCastOfRetainFn(IGF.IGM, fn, value->getType());
auto call = IGF.Builder.CreateCall(fn, value);
call->setDoesNotThrow();
call->setTailCall(); // force tail calls at -O0
return call;
}
namespace {
/// A type-info implementation suitable for an ObjC pointer type.
class ObjCTypeInfo : public HeapTypeInfo<ObjCTypeInfo> {
public:
ObjCTypeInfo(llvm::PointerType *storageType, Size size,
SpareBitVector spareBits, Alignment align)
: HeapTypeInfo(storageType, size, spareBits, align) {
}
/// Builtin.UnknownObject requires ObjC reference-counting.
ReferenceCounting getReferenceCounting() const {
return ReferenceCounting::ObjC;
}
};
}
const LoadableTypeInfo *TypeConverter::convertBuiltinUnknownObject() {
return new ObjCTypeInfo(IGM.ObjCPtrTy, IGM.getPointerSize(),
IGM.getHeapObjectSpareBits(),
IGM.getPointerAlignment());
}
namespace {
/// A type info implementation for BridgeObject
class BridgeObjectTypeInfo : public HeapTypeInfo<BridgeObjectTypeInfo> {
public:
BridgeObjectTypeInfo(llvm::PointerType *storageType, Size size,
SpareBitVector spareBits, Alignment align)
: HeapTypeInfo(storageType, size, spareBits, align) {
}
/// Builtin.BridgeObject uses its own specialized refcounting implementation.
ReferenceCounting getReferenceCounting() const {
return ReferenceCounting::Bridge;
}
// BridgeObject exposes only null as an extra inhabitant for enum layout.
// Other representations are reserved for future use by the stdlib.
bool mayHaveExtraInhabitants(IRGenModule &IGM) const override {
return true;
}
unsigned getFixedExtraInhabitantCount(IRGenModule &IGM) const override {
return 1;
}
APInt getFixedExtraInhabitantValue(IRGenModule &IGM,
unsigned bits,
unsigned index) const override {
return APInt(bits, 0);
}
llvm::Value *getExtraInhabitantIndex(IRGenFunction &IGF, Address src,
SILType T) const override {
src = IGF.Builder.CreateBitCast(src, IGF.IGM.SizeTy->getPointerTo());
auto val = IGF.Builder.CreateLoad(src);
auto isNonzero = IGF.Builder.CreateICmpNE(val,
llvm::ConstantInt::get(IGF.IGM.SizeTy, 0));
// We either have extra inhabitant 0 or no extra inhabitant (-1).
// Conveniently, this is just a sext i1 -> i32 away.
return IGF.Builder.CreateSExt(isNonzero, IGF.IGM.Int32Ty);
}
void storeExtraInhabitant(IRGenFunction &IGF, llvm::Value *index,
Address dest, SILType T) const override {
// There's only one extra inhabitant, 0.
dest = IGF.Builder.CreateBitCast(dest, IGF.IGM.SizeTy->getPointerTo());
IGF.Builder.CreateStore(llvm::ConstantInt::get(IGF.IGM.SizeTy, 0), dest);
}
};
}
const LoadableTypeInfo *TypeConverter::convertBuiltinBridgeObject() {
return new BridgeObjectTypeInfo(IGM.BridgeObjectPtrTy, IGM.getPointerSize(),
SpareBitVector::getConstant(IGM.getPointerSize().getValueInBits(), false),
IGM.getPointerAlignment());
}
const TypeInfo &IRGenModule::getObjCClassPtrTypeInfo() {
return Types.getObjCClassPtrTypeInfo();
}
const LoadableTypeInfo &TypeConverter::getObjCClassPtrTypeInfo() {
// ObjC class pointers look like unmanaged (untagged) object references.
if (ObjCClassPtrTI) return *ObjCClassPtrTI;
ObjCClassPtrTI =
createUnmanagedStorageType(IGM.ObjCClassPtrTy);
ObjCClassPtrTI->NextConverted = FirstType;
FirstType = ObjCClassPtrTI;
return *ObjCClassPtrTI;
}
/// Get or create a global Objective-C method name. Always returns an i8*.
llvm::Constant *IRGenModule::getAddrOfObjCMethodName(StringRef selector) {
// Check whether this selector already exists.
auto &entry = ObjCMethodNames[selector];
if (entry) return entry;
// If not, create it. This implicitly adds a trailing null.
auto init = llvm::ConstantDataArray::getString(LLVMContext, selector);
auto global = new llvm::GlobalVariable(Module, init->getType(), true,
llvm::GlobalValue::InternalLinkage,
init,
llvm::Twine("\01L_selector_data(") + selector + ")");
global->setSection("__TEXT,__objc_methname,cstring_literals");
global->setAlignment(1);
// Drill down to make an i8*.
auto zero = llvm::ConstantInt::get(SizeTy, 0);
llvm::Constant *indices[] = { zero, zero };
auto address = llvm::ConstantExpr::getInBoundsGetElementPtr(
init->getType(), global, indices);
// Cache and return.
entry = address;
return address;
}
/// Get or create an Objective-C selector reference. Always returns
/// an i8**. The design is that the compiler will emit a load of this
/// pointer, and the linker will ensure that that pointer is unique.
llvm::Constant *IRGenModule::getAddrOfObjCSelectorRef(StringRef selector) {
// Check whether a reference for this selector already exists.
auto &entry = ObjCSelectorRefs[selector];
if (entry) return entry;
// If not, create it. The initializer is just a pointer to the
// method name. Note that the label here is unimportant, so we
// choose something descriptive to make the IR readable.
auto init = getAddrOfObjCMethodName(selector);
auto global = new llvm::GlobalVariable(Module, init->getType(), false,
llvm::GlobalValue::InternalLinkage,
init,
llvm::Twine("\01L_selector(") + selector + ")");
global->setAlignment(getPointerAlignment().getValue());
// This section name is magical for the Darwin static and dynamic linkers.
global->setSection("__DATA,__objc_selrefs,literal_pointers,no_dead_strip");
// Make sure that this reference does not get optimized away.
addUsedGlobal(global);
// Cache and return.
entry = global;
return global;
}
/// Get or create an ObjC protocol record. Always returns an i8*. We lazily
/// create ObjC protocol_t records for protocols, storing references to the
/// record into the __objc_protolist and and __objc_protorefs sections to be
/// fixed up by the runtime.
///
/// It is not correct to use this value as a Protocol* reference directly. The
/// ObjC runtime requires protocol references to be loaded from an
/// indirect variable, the address of which is given by
/// getAddrOfObjCProtocolRef.
llvm::Constant *IRGenModule::getAddrOfObjCProtocolRecord(ProtocolDecl *proto,
ForDefinition_t forDefinition) {
return const_cast<llvm::Constant*>
(cast<llvm::Constant>(getObjCProtocolGlobalVars(proto).record));
}
/// Get or create an ObjC protocol reference. Always returns an i8**. We lazily
/// create ObjC protocol_t records for protocols, storing references to the
/// record into the __objc_protolist and and __objc_protorefs sections to be
/// fixed up by the runtime.
llvm::Constant *IRGenModule::getAddrOfObjCProtocolRef(ProtocolDecl *proto,
ForDefinition_t forDefinition) {
return const_cast<llvm::Constant*>
(cast<llvm::Constant>(getObjCProtocolGlobalVars(proto).ref));
}
IRGenModule::ObjCProtocolPair
IRGenModule::getObjCProtocolGlobalVars(ProtocolDecl *proto) {
// See whether we already emitted this protocol reference.
auto found = ObjCProtocols.find(proto);
if (found != ObjCProtocols.end()) {
return found->second;
}
// Create a placeholder protocol record.
llvm::Constant *protocolRecord =
new llvm::GlobalVariable(Module, Int8Ty, /*constant*/ false,
llvm::GlobalValue::PrivateLinkage, nullptr);
LazyObjCProtocolDefinitions.push_back(proto);
// Introduce a variable to label the protocol.
llvm::SmallString<64> nameBuffer;
StringRef protocolName = proto->getObjCRuntimeName(nameBuffer);
auto *protocolLabel
= new llvm::GlobalVariable(Module, Int8PtrTy,
/*constant*/ false,
llvm::GlobalValue::WeakAnyLinkage,
protocolRecord,
llvm::Twine("\01l_OBJC_LABEL_PROTOCOL_$_")
+ protocolName);
protocolLabel->setAlignment(getPointerAlignment().getValue());
protocolLabel->setVisibility(llvm::GlobalValue::HiddenVisibility);
protocolLabel->setSection("__DATA,__objc_protolist,coalesced,no_dead_strip");
// Introduce a variable to reference the protocol.
auto *protocolRef
= new llvm::GlobalVariable(Module, Int8PtrTy,
/*constant*/ false,
llvm::GlobalValue::WeakAnyLinkage,
protocolRecord,
llvm::Twine("\01l_OBJC_PROTOCOL_REFERENCE_$_")
+ protocolName);
protocolRef->setAlignment(getPointerAlignment().getValue());
protocolRef->setVisibility(llvm::GlobalValue::HiddenVisibility);
protocolRef->setSection("__DATA,__objc_protorefs,coalesced,no_dead_strip");
ObjCProtocolPair pair{protocolRecord, protocolRef};
ObjCProtocols.insert({proto, pair});
return pair;
}
void IRGenModule::emitLazyObjCProtocolDefinition(ProtocolDecl *proto) {
// Emit the real definition.
auto record = cast<llvm::GlobalVariable>(emitObjCProtocolData(*this, proto));
// Find the placeholder. It should always still be a placeholder,
// because it was created as an anonymous symbol and nobody should
// ever be randomly messing with those.
auto placeholder =
cast<llvm::GlobalVariable>(ObjCProtocols.find(proto)->second.record);
// Move the new record to the placeholder's position.
Module.getGlobalList().remove(record);
Module.getGlobalList().insertAfter(placeholder->getIterator(), record);
// Replace and destroy the placeholder.
placeholder->replaceAllUsesWith(
llvm::ConstantExpr::getBitCast(record, Int8PtrTy));
placeholder->eraseFromParent();
}
void IRGenModule::emitLazyObjCProtocolDefinitions() {
// Emit any lazy ObjC protocol definitions we require. Try to do
// this in the order in which we needed them, since they can require
// other protocol definitions recursively.
for (size_t i = 0; i != LazyObjCProtocolDefinitions.size(); ++i) {
ProtocolDecl *protocol = LazyObjCProtocolDefinitions[i];
emitLazyObjCProtocolDefinition(protocol);
}
}
namespace {
class Selector {
llvm::SmallString<80> Buffer;
StringRef Text;
public:
static constexpr struct ForGetter_t { } ForGetter{};
static constexpr struct ForSetter_t { } ForSetter{};
#define FOREACH_FAMILY(FAMILY) \
FAMILY(Alloc, "alloc") \
FAMILY(Copy, "copy") \
FAMILY(Init, "init") \
FAMILY(MutableCopy, "mutableCopy") \
FAMILY(New, "new")
// Note that these are in parallel with 'prefixes', below.
enum class Family {
None,
#define GET_LABEL(LABEL, PREFIX) LABEL,
FOREACH_FAMILY(GET_LABEL)
#undef GET_LABEL
};
Selector() = default;
Selector(FuncDecl *method) {
Text = method->getObjCSelector().getString(Buffer);
}
Selector(ConstructorDecl *ctor) {
Text = ctor->getObjCSelector().getString(Buffer);
}
Selector(ValueDecl *methodOrCtorOrDtor) {
if (auto *method = dyn_cast<FuncDecl>(methodOrCtorOrDtor)) {
Text = method->getObjCSelector().getString(Buffer);
} else if (auto *ctor = dyn_cast<ConstructorDecl>(methodOrCtorOrDtor)) {
Text = ctor->getObjCSelector().getString(Buffer);
} else if (isa<DestructorDecl>(methodOrCtorOrDtor)) {
Text = "dealloc";
} else {
llvm_unreachable("property or subscript selector should be generated "
"using ForGetter or ForSetter constructors");
}
}
Selector(AbstractStorageDecl *asd, ForGetter_t) {
Text = asd->getObjCGetterSelector().getString(Buffer);
}
Selector(AbstractStorageDecl *asd, ForSetter_t) {
Text = asd->getObjCSetterSelector().getString(Buffer);
}
Selector(SILDeclRef ref) {
switch (ref.kind) {
case SILDeclRef::Kind::DefaultArgGenerator:
case SILDeclRef::Kind::EnumElement:
case SILDeclRef::Kind::GlobalAccessor:
case SILDeclRef::Kind::GlobalGetter:
llvm_unreachable("Method does not have a selector");
case SILDeclRef::Kind::Destroyer:
case SILDeclRef::Kind::Deallocator:
Text = "dealloc";
break;
case SILDeclRef::Kind::Func:
Text = cast<FuncDecl>(ref.getDecl())->getObjCSelector()
.getString(Buffer);
break;
case SILDeclRef::Kind::Allocator:
case SILDeclRef::Kind::Initializer:
Text = cast<ConstructorDecl>(ref.getDecl())->getObjCSelector()
.getString(Buffer);
break;
case SILDeclRef::Kind::IVarInitializer:
Text = ".cxx_construct";
break;
case SILDeclRef::Kind::IVarDestroyer:
Text = ".cxx_destruct";
break;
}
}
StringRef str() const {
return Text;
}
/// Return the family string of this selector.
Family getFamily() const {
StringRef text = str();
while (!text.empty() && text[0] == '_') text = text.substr(1);
#define CHECK_PREFIX(LABEL, PREFIX) \
if (hasPrefix(text, PREFIX)) return Family::LABEL;
FOREACH_FAMILY(CHECK_PREFIX)
#undef CHECK_PREFIX
return Family::None;
}
private:
/// Does the given selector start with the given string as a
/// prefix, in the sense of the selector naming conventions?
static bool hasPrefix(StringRef text, StringRef prefix) {
if (!text.startswith(prefix)) return false;
if (text.size() == prefix.size()) return true;
assert(text.size() > prefix.size());
return !islower(text[prefix.size()]);
}
#undef FOREACH_FAMILY
};
}
static void emitSuperArgument(IRGenFunction &IGF, bool isInstanceMethod,
llvm::Value *selfValue,
Explosion &selfValues,
SILType searchClass) {
// Allocate an objc_super struct.
Address super = IGF.createAlloca(IGF.IGM.ObjCSuperStructTy,
IGF.IGM.getPointerAlignment(),
"objc_super");
llvm::Value *self = IGF.Builder.CreateBitCast(selfValue,
IGF.IGM.ObjCPtrTy);
// Generate the search class object reference.
llvm::Value *searchValue;
if (isInstanceMethod) {
searchValue = emitClassHeapMetadataRef(IGF, searchClass.getSwiftRValueType(),
MetadataValueType::ObjCClass,
/*allow uninitialized*/ true);
} else {
ClassDecl *searchClassDecl =
searchClass.castTo<MetatypeType>().getInstanceType()
.getClassOrBoundGenericClass();
searchValue = IGF.IGM.getAddrOfMetaclassObject(searchClassDecl,
NotForDefinition);
}
// Store the receiver and class to the struct.
llvm::Value *selfIndices[2] = {
IGF.Builder.getInt32(0),
IGF.Builder.getInt32(0)
};
llvm::Value *selfAddr = IGF.Builder.CreateGEP(super.getAddress(),
selfIndices);
IGF.Builder.CreateStore(self, selfAddr, super.getAlignment());
llvm::Value *searchIndices[2] = {
IGF.Builder.getInt32(0),
IGF.Builder.getInt32(1)
};
llvm::Value *searchAddr = IGF.Builder.CreateGEP(super.getAddress(),
searchIndices);
IGF.Builder.CreateStore(searchValue, searchAddr, super.getAlignment());
// Pass a pointer to the objc_super struct to the messenger.
// Project the ownership semantics of 'self' to the super argument.
selfValues.add(super.getAddress());
}
static llvm::FunctionType *getMsgSendSuperTy(IRGenModule &IGM,
llvm::FunctionType *fnTy,
bool indirectResult) {
SmallVector<llvm::Type*, 4> args(fnTy->param_begin(), fnTy->param_end());
if (indirectResult)
args[1] = IGM.ObjCSuperPtrTy;
else
args[0] = IGM.ObjCSuperPtrTy;
return llvm::FunctionType::get(fnTy->getReturnType(), args, fnTy->isVarArg());
}
/// Prepare a call using ObjC method dispatch without applying the 'self' and
/// '_cmd' arguments.
CallEmission irgen::prepareObjCMethodRootCall(IRGenFunction &IGF,
SILDeclRef method,
CanSILFunctionType origFnType,
CanSILFunctionType substFnType,
ArrayRef<Substitution> subs,
ObjCMessageKind kind) {
assert((method.kind == SILDeclRef::Kind::Initializer
|| method.kind == SILDeclRef::Kind::Allocator
|| method.kind == SILDeclRef::Kind::Func
|| method.kind == SILDeclRef::Kind::Destroyer
|| method.kind == SILDeclRef::Kind::Deallocator) &&
"objc method call must be to a func/initializer/getter/setter/dtor");
llvm::AttributeSet attrs;
auto fnTy = IGF.IGM.getFunctionType(origFnType, attrs);
bool indirectResult = requiresExternalIndirectResult(IGF.IGM, origFnType);
if (kind != ObjCMessageKind::Normal)
fnTy = getMsgSendSuperTy(IGF.IGM, fnTy, indirectResult);
// Create the appropriate messenger function.
// FIXME: this needs to be target-specific.
llvm::Constant *messenger;
if (indirectResult && IGF.IGM.TargetInfo.ObjCUseStret) {
switch (kind) {
case ObjCMessageKind::Normal:
messenger = IGF.IGM.getObjCMsgSendStretFn();
break;
case ObjCMessageKind::Peer:
messenger = IGF.IGM.getObjCMsgSendSuperStretFn();
break;
case ObjCMessageKind::Super:
messenger = IGF.IGM.getObjCMsgSendSuperStret2Fn();
break;
}
} else {
switch (kind) {
case ObjCMessageKind::Normal:
messenger = IGF.IGM.getObjCMsgSendFn();
break;
case ObjCMessageKind::Peer:
messenger = IGF.IGM.getObjCMsgSendSuperFn();
break;
case ObjCMessageKind::Super:
messenger = IGF.IGM.getObjCMsgSendSuper2Fn();
break;
}
}
// Cast the messenger to the right type.
messenger = llvm::ConstantExpr::getBitCast(messenger, fnTy->getPointerTo());
CallEmission emission(IGF,
Callee::forKnownFunction(origFnType,
substFnType,
subs,
messenger, nullptr));
return emission;
}
/// Emit the 'self'/'super' and '_cmd' arguments for an ObjC method dispatch.
void irgen::addObjCMethodCallImplicitArguments(IRGenFunction &IGF,
Explosion &args,
SILDeclRef method,
llvm::Value *self,
SILType searchType) {
// Compute the selector.
Selector selector(method);
// super.constructor references an instance method (even though the
// decl is really a 'static' member). Similarly, destructors refer
// to the instance method -dealloc.
bool isInstanceMethod
= method.kind == SILDeclRef::Kind::Initializer
|| method.kind == SILDeclRef::Kind::Deallocator
|| method.getDecl()->isInstanceMember();
if (searchType) {
emitSuperArgument(IGF, isInstanceMethod, self, args, searchType);
} else {
args.add(self);
}
assert(args.size() == 1);
// Add the selector value.
args.add(IGF.emitObjCSelectorRefLoad(selector.str()));
}
/// Return the formal type that we would use for +allocWithZone:.
static CanSILFunctionType getAllocObjectFormalType(ASTContext &ctx,
CanType classType) {
SILParameterInfo inputs[] = {
SILParameterInfo(CanType(ctx.TheRawPointerType), /* (NSZone*), kindof */
ParameterConvention::Direct_Unowned),
SILParameterInfo(CanType(MetatypeType::get(classType,
MetatypeRepresentation::Thick)),
ParameterConvention::Direct_Unowned)
};
auto result = SILResultInfo(classType, ResultConvention::Owned);
auto extInfo = SILFunctionType::ExtInfo(SILFunctionType::Representation::ObjCMethod,
/*noreturn*/ false);
return SILFunctionType::get(nullptr, extInfo,
/*callee*/ ParameterConvention::Direct_Unowned,
inputs, result, None, ctx);
}
/// Call [self allocWithZone: nil].
llvm::Value *irgen::emitObjCAllocObjectCall(IRGenFunction &IGF,
llvm::Value *self,
CanType classType) {
// Compute the formal type that we expect +allocWithZone: to have.
auto formalType = getAllocObjectFormalType(IGF.IGM.Context, classType);
// Compute the appropriate LLVM type for the function.
llvm::AttributeSet attrs;
auto fnTy = IGF.IGM.getFunctionType(formalType, attrs);
// Get the messenger function.
llvm::Constant *messenger = IGF.IGM.getObjCMsgSendFn();
messenger = llvm::ConstantExpr::getBitCast(messenger, fnTy->getPointerTo());
// Prepare the call.
CallEmission emission(IGF, Callee::forKnownFunction(formalType,
formalType, {},
messenger, nullptr));
// Emit the arguments.
{
Explosion args;
args.add(self);
args.add(IGF.emitObjCSelectorRefLoad("allocWithZone:"));
args.add(llvm::ConstantPointerNull::get(IGF.IGM.Int8PtrTy));
emission.setArgs(args, {});
}
// Emit the call.
Explosion out;
emission.emitToExplosion(out);
return out.claimNext();
}
static llvm::Function *emitObjCPartialApplicationForwarder(IRGenModule &IGM,
SILDeclRef method,
CanSILFunctionType origMethodType,
CanSILFunctionType resultType,
const HeapLayout &layout,
SILType selfType) {
auto &selfTI = IGM.getTypeInfo(selfType);
assert(resultType->getRepresentation()
== SILFunctionType::Representation::Thick);
llvm::AttributeSet attrs;
llvm::FunctionType *fwdTy = IGM.getFunctionType(resultType, attrs);
// FIXME: Give the thunk a real name.
// FIXME: Maybe cache the thunk by function and closure types?
llvm::Function *fwd =
llvm::Function::Create(fwdTy, llvm::Function::InternalLinkage,
"_TPAo", &IGM.Module);
auto initialAttrs = IGM.constructInitialAttributes();
// Merge initialAttrs with attrs.
auto updatedAttrs = attrs.addAttributes(IGM.getLLVMContext(),
llvm::AttributeSet::FunctionIndex, initialAttrs);
fwd->setAttributes(updatedAttrs);
IRGenFunction subIGF(IGM, fwd);
// Do we need to lifetime-extend self?
bool lifetimeExtendsSelf;
switch (origMethodType->getResult().getConvention()) {
case ResultConvention::UnownedInnerPointer:
lifetimeExtendsSelf = true;
break;
case ResultConvention::Unowned:
case ResultConvention::Owned:
case ResultConvention::Autoreleased:
lifetimeExtendsSelf = false;
break;
}
// Do we need to retain self before calling, and/or release it after?
bool retainsSelf;
switch (origMethodType->getParameters().back().getConvention()) {
case ParameterConvention::Direct_Unowned:
case ParameterConvention::Direct_Deallocating:
retainsSelf = false;
break;
case ParameterConvention::Direct_Guaranteed:
case ParameterConvention::Direct_Owned:
retainsSelf = true;
break;
case ParameterConvention::Indirect_In_Guaranteed:
case ParameterConvention::Indirect_In:
case ParameterConvention::Indirect_Out:
case ParameterConvention::Indirect_Inout:
llvm_unreachable("self passed indirectly?!");
}
// Recover 'self' from the context.
Explosion params = subIGF.collectParameters();
llvm::Value *context = params.takeLast();
Address dataAddr = layout.emitCastTo(subIGF, context);
auto &fieldLayout = layout.getElement(0);
Address selfAddr = fieldLayout.project(subIGF, dataAddr, None);
Explosion selfParams;
if (retainsSelf)
cast<LoadableTypeInfo>(selfTI).loadAsCopy(subIGF, selfAddr, selfParams);
else
cast<LoadableTypeInfo>(selfTI).loadAsTake(subIGF, selfAddr, selfParams);
llvm::Value *self = selfParams.claimNext();
// Save off the forwarded indirect return address if we have one.
llvm::Value *indirectReturn = nullptr;
SILType appliedResultTy = origMethodType->getSemanticResultSILType();
auto &appliedResultTI = IGM.getTypeInfo(appliedResultTy);
if (appliedResultTI.getSchema().requiresIndirectResult(IGM)) {
indirectReturn = params.claimNext();
}
// Prepare the call to the underlying method.
CallEmission emission
= prepareObjCMethodRootCall(subIGF, method, origMethodType, origMethodType,
ArrayRef<Substitution>{},
ObjCMessageKind::Normal);
Explosion args;
addObjCMethodCallImplicitArguments(subIGF, args, method, self, SILType());
args.add(params.claimAll());
emission.setArgs(args, {});
// Cleanup that always has to occur after the function call.
auto cleanup = [&]{
// Lifetime-extend 'self' by sending it to the autorelease pool if need be.
if (lifetimeExtendsSelf) {
subIGF.emitObjCRetainCall(self);
subIGF.emitObjCAutoreleaseCall(self);
}
// Release the context.
subIGF.emitRelease(context);
};
// Emit the call and produce the return value.
if (indirectReturn) {
emission.emitToMemory(appliedResultTI.getAddressForPointer(indirectReturn),
appliedResultTI);
cleanup();
subIGF.Builder.CreateRetVoid();
} else {
Explosion result;
emission.emitToExplosion(result);
cleanup();
auto &callee = emission.getCallee();
auto resultType = callee.getOrigFunctionType()->getSILResult();
subIGF.emitScalarReturn(resultType, result);
}
return fwd;
}
void irgen::emitObjCPartialApplication(IRGenFunction &IGF,
SILDeclRef method,
CanSILFunctionType origMethodType,
CanSILFunctionType resultType,
llvm::Value *self,
SILType selfType,
Explosion &out) {
// Create a heap object to contain the self argument.
// TODO: If function context arguments were given objc retain counts,
// we wouldn't need to create a separate heap object here.
auto *selfTypeInfo = &IGF.getTypeInfo(selfType);
HeapLayout layout(IGF.IGM, LayoutStrategy::Optimal,
selfType, selfTypeInfo);
llvm::Value *data = IGF.emitUnmanagedAlloc(layout, "closure");
// FIXME: non-fixed offsets
NonFixedOffsets offsets = None;
Address dataAddr = layout.emitCastTo(IGF, data);
auto &fieldLayout = layout.getElement(0);
auto &fieldType = layout.getElementTypes()[0];
Address fieldAddr = fieldLayout.project(IGF, dataAddr, offsets);
Explosion selfParams;
selfParams.add(self);
fieldLayout.getType().initializeFromParams(IGF, selfParams,
fieldAddr, fieldType);
// Create the forwarding stub.
llvm::Function *forwarder = emitObjCPartialApplicationForwarder(IGF.IGM,
method,
origMethodType,
resultType,
layout,
selfType);
llvm::Value *forwarderValue = IGF.Builder.CreateBitCast(forwarder,
IGF.IGM.Int8PtrTy);
// Emit the result explosion.
out.add(forwarderValue);
out.add(data);
}
/// Create the LLVM function declaration for a thunk that acts like
/// an Objective-C method for a Swift method implementation.
static llvm::Constant *findSwiftAsObjCThunk(IRGenModule &IGM, SILDeclRef ref) {
SILFunction *SILFn = IGM.SILMod->lookUpFunction(ref);
assert(SILFn && "no IR function for swift-as-objc thunk");
auto fn = IGM.getAddrOfSILFunction(SILFn, NotForDefinition);
// FIXME: Should set the linkage of the SILFunction to 'internal'.
fn->setVisibility(llvm::GlobalValue::DefaultVisibility);
fn->setLinkage(llvm::GlobalValue::InternalLinkage);
fn->setUnnamedAddr(true);
return llvm::ConstantExpr::getBitCast(fn, IGM.Int8PtrTy);
}
/// Produce a function pointer, suitable for invocation by
/// objc_msgSend, for the given property's getter method implementation.
///
/// Returns a value of type i8*.
static llvm::Constant *getObjCGetterPointer(IRGenModule &IGM,
AbstractStorageDecl *property) {
// Protocol properties have no impl.
if (isa<ProtocolDecl>(property->getDeclContext()))
return llvm::ConstantPointerNull::get(IGM.Int8PtrTy);
// FIXME: Explosion level
ResilienceExpansion expansion = ResilienceExpansion::Minimal;
SILDeclRef getter = SILDeclRef(property->getGetter(), SILDeclRef::Kind::Func,
expansion,
SILDeclRef::ConstructAtNaturalUncurryLevel,
/*foreign*/ true);
return findSwiftAsObjCThunk(IGM, getter);
}
/// Produce a function pointer, suitable for invocation by
/// objc_msgSend, for the given property's setter method implementation.
///
/// Returns a value of type i8*.
static llvm::Constant *getObjCSetterPointer(IRGenModule &IGM,
AbstractStorageDecl *property) {
// Protocol properties have no impl.
if (isa<ProtocolDecl>(property->getDeclContext()))
return llvm::ConstantPointerNull::get(IGM.Int8PtrTy);
assert(property->isSettable(property->getDeclContext()) &&
"property is not settable?!");
ResilienceExpansion expansion = ResilienceExpansion::Minimal;
SILDeclRef setter = SILDeclRef(property->getSetter(), SILDeclRef::Kind::Func,
expansion,
SILDeclRef::ConstructAtNaturalUncurryLevel,
/*foreign*/ true);
return findSwiftAsObjCThunk(IGM, setter);
}
/// Produce a function pointer, suitable for invocation by
/// objc_msgSend, for the given method implementation.
///
/// Returns a value of type i8*.
static llvm::Constant *getObjCMethodPointer(IRGenModule &IGM,
FuncDecl *method) {
// Protocol methods have no impl.
if (isa<ProtocolDecl>(method->getDeclContext()))
return llvm::ConstantPointerNull::get(IGM.Int8PtrTy);
ResilienceExpansion expansion = ResilienceExpansion::Minimal;
SILDeclRef declRef = SILDeclRef(method, SILDeclRef::Kind::Func,
expansion,
SILDeclRef::ConstructAtNaturalUncurryLevel,