forked from swiftlang/swift
-
Notifications
You must be signed in to change notification settings - Fork 0
/
GenHeap.cpp
1980 lines (1788 loc) · 81.9 KB
/
GenHeap.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
//===--- GenHeap.cpp - Layout of heap objects and their metadata ----------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
//
// This file implements routines for arbitrary Swift-native heap objects,
// such as layout and reference-counting.
//
//===----------------------------------------------------------------------===//
#include "llvm/Support/ErrorHandling.h"
#include "llvm/Support/Compiler.h"
#include "llvm/Support/Path.h"
#include "llvm/IR/DerivedTypes.h"
#include "llvm/IR/Function.h"
#include "llvm/IR/GlobalVariable.h"
#include "llvm/IR/Intrinsics.h"
#include "swift/Basic/SourceLoc.h"
#include "swift/ABI/MetadataValues.h"
#include "swift/AST/ASTContext.h"
#include "swift/AST/GenericEnvironment.h"
#include "swift/AST/IRGenOptions.h"
#include "swift/SIL/SILModule.h"
#include "ConstantBuilder.h"
#include "Explosion.h"
#include "GenClass.h"
#include "GenProto.h"
#include "GenType.h"
#include "IRGenDebugInfo.h"
#include "IRGenFunction.h"
#include "IRGenModule.h"
#include "HeapTypeInfo.h"
#include "IndirectTypeInfo.h"
#include "MetadataRequest.h"
#include "GenHeap.h"
using namespace swift;
using namespace irgen;
namespace {
#define NEVER_LOADABLE_CHECKED_REF_STORAGE_HELPER(Name, Nativeness) \
class Nativeness##Name##ReferenceTypeInfo \
: public IndirectTypeInfo<Nativeness##Name##ReferenceTypeInfo, \
FixedTypeInfo> { \
llvm::PointerIntPair<llvm::Type*, 1, bool> ValueTypeAndIsOptional; \
public: \
Nativeness##Name##ReferenceTypeInfo(llvm::Type *valueType, \
llvm::Type *type, \
Size size, Alignment alignment, \
SpareBitVector &&spareBits, \
bool isOptional) \
: IndirectTypeInfo(type, size, std::move(spareBits), alignment, \
IsNotPOD, IsNotBitwiseTakable, IsFixedSize), \
ValueTypeAndIsOptional(valueType, isOptional) {} \
void initializeWithCopy(IRGenFunction &IGF, Address destAddr, \
Address srcAddr, SILType T, \
bool isOutlined) const override { \
IGF.emit##Nativeness##Name##CopyInit(destAddr, srcAddr); \
} \
void initializeWithTake(IRGenFunction &IGF, Address destAddr, \
Address srcAddr, SILType T, \
bool isOutlined) const override { \
IGF.emit##Nativeness##Name##TakeInit(destAddr, srcAddr); \
} \
void assignWithCopy(IRGenFunction &IGF, Address destAddr, Address srcAddr, \
SILType T, bool isOutlined) const override { \
IGF.emit##Nativeness##Name##CopyAssign(destAddr, srcAddr); \
} \
void assignWithTake(IRGenFunction &IGF, Address destAddr, Address srcAddr, \
SILType T, bool isOutlined) const override { \
IGF.emit##Nativeness##Name##TakeAssign(destAddr, srcAddr); \
} \
void destroy(IRGenFunction &IGF, Address addr, SILType T, \
bool isOutlined) const override { \
IGF.emit##Nativeness##Name##Destroy(addr); \
} \
unsigned getFixedExtraInhabitantCount(IRGenModule &IGM) const override { \
auto count = IGM.getReferenceStorageExtraInhabitantCount( \
ReferenceOwnership::Name, \
ReferenceCounting::Nativeness); \
return count - ValueTypeAndIsOptional.getInt(); \
} \
APInt getFixedExtraInhabitantValue(IRGenModule &IGM, \
unsigned bits, \
unsigned index) const override { \
return IGM.getReferenceStorageExtraInhabitantValue(bits, \
index + ValueTypeAndIsOptional.getInt(), \
ReferenceOwnership::Name, \
ReferenceCounting::Nativeness); \
} \
llvm::Value *getExtraInhabitantIndex(IRGenFunction &IGF, Address src, \
SILType T, bool isOutlined) \
const override { \
return IGF.getReferenceStorageExtraInhabitantIndex(src, \
ReferenceOwnership::Name, \
ReferenceCounting::Nativeness); \
} \
void storeExtraInhabitant(IRGenFunction &IGF, llvm::Value *index, \
Address dest, SILType T, bool isOutlined) \
const override { \
return IGF.storeReferenceStorageExtraInhabitant(index, dest, \
ReferenceOwnership::Name, \
ReferenceCounting::Nativeness); \
} \
APInt getFixedExtraInhabitantMask(IRGenModule &IGM) const override { \
return IGM.getReferenceStorageExtraInhabitantMask( \
ReferenceOwnership::Name, \
ReferenceCounting::Nativeness); \
} \
llvm::Type *getOptionalIntType() const { \
return llvm::IntegerType::get( \
ValueTypeAndIsOptional.getPointer()->getContext(), \
getFixedSize().getValueInBits()); \
} \
};
#define ALWAYS_LOADABLE_CHECKED_REF_STORAGE_HELPER(Name, Nativeness) \
class Nativeness##Name##ReferenceTypeInfo \
: public SingleScalarTypeInfo<Nativeness##Name##ReferenceTypeInfo, \
LoadableTypeInfo> { \
llvm::PointerIntPair<llvm::Type*, 1, bool> ValueTypeAndIsOptional; \
public: \
Nativeness##Name##ReferenceTypeInfo(llvm::Type *valueType, \
llvm::Type *type, \
Size size, Alignment alignment, \
SpareBitVector &&spareBits, \
bool isOptional) \
: SingleScalarTypeInfo(type, size, std::move(spareBits), \
alignment, IsNotPOD, IsFixedSize), \
ValueTypeAndIsOptional(valueType, isOptional) {} \
enum { IsScalarPOD = false }; \
llvm::Type *getScalarType() const { \
return ValueTypeAndIsOptional.getPointer(); \
} \
Address projectScalar(IRGenFunction &IGF, Address addr) const { \
return IGF.Builder.CreateBitCast(addr, getScalarType()->getPointerTo()); \
} \
void emitScalarRetain(IRGenFunction &IGF, llvm::Value *value, \
Atomicity atomicity) const { \
IGF.emit##Nativeness##Name##Retain(value, atomicity); \
} \
void emitScalarRelease(IRGenFunction &IGF, llvm::Value *value, \
Atomicity atomicity) const { \
IGF.emit##Nativeness##Name##Release(value, atomicity); \
} \
void emitScalarFixLifetime(IRGenFunction &IGF, llvm::Value *value) const { \
IGF.emitFixLifetime(value); \
} \
unsigned getFixedExtraInhabitantCount(IRGenModule &IGM) const override { \
auto count = IGM.getReferenceStorageExtraInhabitantCount( \
ReferenceOwnership::Name, \
ReferenceCounting::Nativeness); \
return count - ValueTypeAndIsOptional.getInt(); \
} \
APInt getFixedExtraInhabitantValue(IRGenModule &IGM, \
unsigned bits, \
unsigned index) const override { \
return IGM.getReferenceStorageExtraInhabitantValue(bits, \
index + ValueTypeAndIsOptional.getInt(), \
ReferenceOwnership::Name, \
ReferenceCounting::Nativeness); \
} \
llvm::Value *getExtraInhabitantIndex(IRGenFunction &IGF, Address src, \
SILType T, bool isOutlined) \
const override { \
return IGF.getReferenceStorageExtraInhabitantIndex(src, \
ReferenceOwnership::Name, \
ReferenceCounting::Nativeness); \
} \
void storeExtraInhabitant(IRGenFunction &IGF, llvm::Value *index, \
Address dest, SILType T, bool isOutlined) \
const override { \
return IGF.storeReferenceStorageExtraInhabitant(index, dest, \
ReferenceOwnership::Name, \
ReferenceCounting::Nativeness); \
} \
APInt getFixedExtraInhabitantMask(IRGenModule &IGM) const override { \
return IGM.getReferenceStorageExtraInhabitantMask( \
ReferenceOwnership::Name, \
ReferenceCounting::Nativeness); \
} \
};
// The nativeness of a reference storage type is a policy decision.
// Please also see the related ALWAYS_NATIVE and SOMETIMES_UNKNOWN macros
// later in this file that expand to the following boilerplate:
// TypeConverter::create##Name##StorageType
NEVER_LOADABLE_CHECKED_REF_STORAGE_HELPER(Weak, Native)
NEVER_LOADABLE_CHECKED_REF_STORAGE_HELPER(Weak, Unknown)
NEVER_LOADABLE_CHECKED_REF_STORAGE_HELPER(Unowned, Unknown)
ALWAYS_LOADABLE_CHECKED_REF_STORAGE_HELPER(Unowned, Native)
#undef NEVER_LOADABLE_CHECKED_REF_STORAGE_HELPER
#undef ALWAYS_LOADABLE_CHECKED_REF_STORAGE_HELPER
#define UNCHECKED_REF_STORAGE(Name, ...) \
class Name##ReferenceTypeInfo \
: public PODSingleScalarTypeInfo<Name##ReferenceTypeInfo, \
LoadableTypeInfo> { \
bool IsOptional; \
public: \
Name##ReferenceTypeInfo(llvm::Type *type, \
const SpareBitVector &spareBits, \
Size size, Alignment alignment, bool isOptional) \
: PODSingleScalarTypeInfo(type, size, spareBits, alignment), \
IsOptional(isOptional) {} \
/* Static types have the same spare bits as managed heap objects. */ \
unsigned getFixedExtraInhabitantCount(IRGenModule &IGM) const override { \
return getHeapObjectExtraInhabitantCount(IGM) - IsOptional; \
} \
APInt getFixedExtraInhabitantValue(IRGenModule &IGM, \
unsigned bits, \
unsigned index) const override { \
return getHeapObjectFixedExtraInhabitantValue(IGM, bits, \
index + IsOptional, 0); \
} \
llvm::Value *getExtraInhabitantIndex(IRGenFunction &IGF, Address src, \
SILType T, bool isOutlined) \
const override { \
return getHeapObjectExtraInhabitantIndex(IGF, src); \
} \
void storeExtraInhabitant(IRGenFunction &IGF, llvm::Value *index, \
Address dest, SILType T, bool isOutlined) \
const override { \
return storeHeapObjectExtraInhabitant(IGF, index, dest); \
} \
};
#include "swift/AST/ReferenceStorage.def"
} // end anonymous namespace
/// Produce a constant to place in a metatype's isa field
/// corresponding to the given metadata kind.
static llvm::ConstantInt *getMetadataKind(IRGenModule &IGM,
MetadataKind kind) {
return llvm::ConstantInt::get(IGM.MetadataKindTy, uint32_t(kind));
}
/// Perform the layout required for a heap object.
HeapLayout::HeapLayout(IRGenModule &IGM, LayoutStrategy strategy,
ArrayRef<SILType> fieldTypes,
ArrayRef<const TypeInfo *> fieldTypeInfos,
llvm::StructType *typeToFill,
NecessaryBindings &&bindings)
: StructLayout(IGM, /*decl=*/nullptr, LayoutKind::HeapObject, strategy,
fieldTypeInfos, typeToFill),
ElementTypes(fieldTypes.begin(), fieldTypes.end()),
Bindings(std::move(bindings))
{
#ifndef NDEBUG
assert(fieldTypeInfos.size() == fieldTypes.size()
&& "type infos don't match types");
if (!Bindings.empty()) {
assert(fieldTypeInfos.size() >= 1 && "no field for bindings");
auto fixedBindingsField = dyn_cast<FixedTypeInfo>(fieldTypeInfos[0]);
assert(fixedBindingsField
&& "bindings field is not fixed size");
assert(fixedBindingsField->getFixedSize()
== Bindings.getBufferSize(IGM)
&& fixedBindingsField->getFixedAlignment()
== IGM.getPointerAlignment()
&& "bindings field doesn't fit bindings");
}
#endif
}
static llvm::Value *calcInitOffset(swift::irgen::IRGenFunction &IGF,
unsigned int i,
const swift::irgen::HeapLayout &layout) {
llvm::Value *offset = nullptr;
if (i == 0) {
auto startoffset = layout.getSize();
offset = llvm::ConstantInt::get(IGF.IGM.SizeTy, startoffset.getValue());
return offset;
}
auto &prevElt = layout.getElement(i - 1);
auto prevType = layout.getElementTypes()[i - 1];
// Start calculating offsets from the last fixed-offset field.
Size lastFixedOffset = layout.getElement(i - 1).getByteOffset();
if (auto *fixedType = dyn_cast<FixedTypeInfo>(&prevElt.getType())) {
// If the last fixed-offset field is also fixed-size, we can
// statically compute the end of the fixed-offset fields.
auto fixedEnd = lastFixedOffset + fixedType->getFixedSize();
offset = llvm::ConstantInt::get(IGF.IGM.SizeTy, fixedEnd.getValue());
} else {
// Otherwise, we need to add the dynamic size to the fixed start
// offset.
offset = llvm::ConstantInt::get(IGF.IGM.SizeTy, lastFixedOffset.getValue());
offset = IGF.Builder.CreateAdd(
offset, prevElt.getType().getSize(IGF, prevType));
}
return offset;
}
HeapNonFixedOffsets::HeapNonFixedOffsets(IRGenFunction &IGF,
const HeapLayout &layout) {
if (!layout.isFixedLayout()) {
// Calculate all the non-fixed layouts.
// TODO: We could be lazier about this.
llvm::Value *offset = nullptr;
llvm::Value *totalAlign = llvm::ConstantInt::get(IGF.IGM.SizeTy,
layout.getAlignment().getMaskValue());
for (unsigned i : indices(layout.getElements())) {
auto &elt = layout.getElement(i);
auto eltTy = layout.getElementTypes()[i];
switch (elt.getKind()) {
case ElementLayout::Kind::InitialNonFixedSize:
// Factor the non-fixed-size field's alignment into the total alignment.
totalAlign = IGF.Builder.CreateOr(totalAlign,
elt.getType().getAlignmentMask(IGF, eltTy));
LLVM_FALLTHROUGH;
case ElementLayout::Kind::Empty:
case ElementLayout::Kind::EmptyTailAllocatedCType:
case ElementLayout::Kind::Fixed:
// Don't need to dynamically calculate this offset.
Offsets.push_back(nullptr);
break;
case ElementLayout::Kind::NonFixed:
// Start calculating non-fixed offsets from the end of the first fixed
// field.
if (!offset) {
offset = calcInitOffset(IGF, i, layout);
}
// Round up to alignment to get the offset.
auto alignMask = elt.getType().getAlignmentMask(IGF, eltTy);
auto notAlignMask = IGF.Builder.CreateNot(alignMask);
offset = IGF.Builder.CreateAdd(offset, alignMask);
offset = IGF.Builder.CreateAnd(offset, notAlignMask);
Offsets.push_back(offset);
// Advance by the field's size to start the next field.
offset = IGF.Builder.CreateAdd(offset,
elt.getType().getSize(IGF, eltTy));
totalAlign = IGF.Builder.CreateOr(totalAlign, alignMask);
break;
}
}
TotalSize = offset;
TotalAlignMask = totalAlign;
} else {
TotalSize = layout.emitSize(IGF.IGM);
TotalAlignMask = layout.emitAlignMask(IGF.IGM);
}
}
void irgen::emitDeallocateHeapObject(IRGenFunction &IGF,
llvm::Value *object,
llvm::Value *size,
llvm::Value *alignMask) {
// FIXME: We should call a fast deallocator for heap objects with
// known size.
IGF.Builder.CreateCall(IGF.IGM.getDeallocObjectFn(),
{object, size, alignMask});
}
void emitDeallocateUninitializedHeapObject(IRGenFunction &IGF,
llvm::Value *object,
llvm::Value *size,
llvm::Value *alignMask) {
IGF.Builder.CreateCall(IGF.IGM.getDeallocUninitializedObjectFn(),
{object, size, alignMask});
}
void irgen::emitDeallocateClassInstance(IRGenFunction &IGF,
llvm::Value *object,
llvm::Value *size,
llvm::Value *alignMask) {
// FIXME: We should call a fast deallocator for heap objects with
// known size.
IGF.Builder.CreateCall(IGF.IGM.getDeallocClassInstanceFn(),
{object, size, alignMask});
}
void irgen::emitDeallocatePartialClassInstance(IRGenFunction &IGF,
llvm::Value *object,
llvm::Value *metadata,
llvm::Value *size,
llvm::Value *alignMask) {
// FIXME: We should call a fast deallocator for heap objects with
// known size.
IGF.Builder.CreateCall(IGF.IGM.getDeallocPartialClassInstanceFn(),
{object, metadata, size, alignMask});
}
/// Create the destructor function for a layout.
/// TODO: give this some reasonable name and possibly linkage.
static llvm::Function *createDtorFn(IRGenModule &IGM,
const HeapLayout &layout) {
llvm::Function *fn =
llvm::Function::Create(IGM.DeallocatingDtorTy,
llvm::Function::PrivateLinkage,
"objectdestroy", &IGM.Module);
auto attrs = IGM.constructInitialAttributes();
IGM.addSwiftSelfAttributes(attrs, 0);
fn->setAttributes(attrs);
fn->setCallingConv(IGM.SwiftCC);
IRGenFunction IGF(IGM, fn);
if (IGM.DebugInfo)
IGM.DebugInfo->emitArtificialFunction(IGF, fn);
Address structAddr = layout.emitCastTo(IGF, &*fn->arg_begin());
// Bind necessary bindings, if we have them.
if (layout.hasBindings()) {
// The type metadata bindings should be at a fixed offset, so we can pass
// None for NonFixedOffsets. If we didn't, we'd have a chicken-egg problem.
auto bindingsAddr = layout.getElement(0).project(IGF, structAddr, None);
layout.getBindings().restore(IGF, bindingsAddr, MetadataState::Complete);
}
// Figure out the non-fixed offsets.
HeapNonFixedOffsets offsets(IGF, layout);
// Destroy the fields.
for (unsigned i : indices(layout.getElements())) {
auto &field = layout.getElement(i);
auto fieldTy = layout.getElementTypes()[i];
if (field.isPOD())
continue;
field.getType().destroy(
IGF, field.project(IGF, structAddr, offsets), fieldTy,
true /*Called from metadata constructors: must be outlined*/);
}
emitDeallocateHeapObject(IGF, &*fn->arg_begin(), offsets.getSize(),
offsets.getAlignMask());
IGF.Builder.CreateRetVoid();
return fn;
}
/// Create the size function for a layout.
/// TODO: give this some reasonable name and possibly linkage.
llvm::Constant *HeapLayout::createSizeFn(IRGenModule &IGM) const {
llvm::Function *fn =
llvm::Function::Create(IGM.DeallocatingDtorTy,
llvm::Function::PrivateLinkage,
"objectsize", &IGM.Module);
fn->setAttributes(IGM.constructInitialAttributes());
IRGenFunction IGF(IGM, fn);
if (IGM.DebugInfo)
IGM.DebugInfo->emitArtificialFunction(IGF, fn);
// Ignore the object pointer; we aren't a dynamically-sized array,
// so it's pointless.
llvm::Value *size = emitSize(IGM);
IGF.Builder.CreateRet(size);
return fn;
}
static llvm::Constant *buildPrivateMetadata(IRGenModule &IGM,
const HeapLayout &layout,
llvm::Constant *dtorFn,
llvm::Constant *captureDescriptor,
MetadataKind kind) {
// Build the fields of the private metadata.
ConstantInitBuilder builder(IGM);
auto fields = builder.beginStruct(IGM.FullBoxMetadataStructTy);
fields.add(dtorFn);
fields.addNullPointer(IGM.WitnessTablePtrTy);
{
auto kindStruct = fields.beginStruct(IGM.TypeMetadataStructTy);
kindStruct.add(getMetadataKind(IGM, kind));
kindStruct.finishAndAddTo(fields);
}
// Figure out the offset to the first element, which is necessary to be able
// to polymorphically project as a generic box.
auto elements = layout.getElements();
Size offset;
if (!elements.empty()
&& elements[0].getKind() == ElementLayout::Kind::Fixed)
offset = elements[0].getByteOffset();
else
offset = Size(0);
fields.addInt32(offset.getValue());
fields.add(captureDescriptor);
llvm::GlobalVariable *var =
fields.finishAndCreateGlobal("metadata",
IGM.getPointerAlignment(),
/*constant*/ true,
llvm::GlobalVariable::PrivateLinkage);
llvm::Constant *indices[] = {
llvm::ConstantInt::get(IGM.Int32Ty, 0),
llvm::ConstantInt::get(IGM.Int32Ty, 2)
};
return llvm::ConstantExpr::getInBoundsGetElementPtr(
/*Ty=*/nullptr, var, indices);
}
llvm::Constant *
HeapLayout::getPrivateMetadata(IRGenModule &IGM,
llvm::Constant *captureDescriptor) const {
if (!privateMetadata)
privateMetadata = buildPrivateMetadata(IGM, *this, createDtorFn(IGM, *this),
captureDescriptor,
MetadataKind::HeapLocalVariable);
return privateMetadata;
}
llvm::Value *IRGenFunction::emitUnmanagedAlloc(const HeapLayout &layout,
const llvm::Twine &name,
llvm::Constant *captureDescriptor,
const HeapNonFixedOffsets *offsets) {
llvm::Value *metadata = layout.getPrivateMetadata(IGM, captureDescriptor);
llvm::Value *size, *alignMask;
if (offsets) {
size = offsets->getSize();
alignMask = offsets->getAlignMask();
} else {
size = layout.emitSize(IGM);
alignMask = layout.emitAlignMask(IGM);
}
return emitAllocObjectCall(metadata, size, alignMask, name);
}
namespace {
class BuiltinNativeObjectTypeInfo
: public HeapTypeInfo<BuiltinNativeObjectTypeInfo> {
public:
BuiltinNativeObjectTypeInfo(llvm::PointerType *storage,
Size size, SpareBitVector spareBits,
Alignment align)
: HeapTypeInfo(storage, size, spareBits, align) {}
/// Builtin.NativeObject uses Swift native reference-counting.
ReferenceCounting getReferenceCounting() const {
return ReferenceCounting::Native;
}
};
} // end anonymous namespace
const LoadableTypeInfo *TypeConverter::convertBuiltinNativeObject() {
return new BuiltinNativeObjectTypeInfo(IGM.RefCountedPtrTy,
IGM.getPointerSize(),
IGM.getHeapObjectSpareBits(),
IGM.getPointerAlignment());
}
unsigned IRGenModule::getReferenceStorageExtraInhabitantCount(
ReferenceOwnership ownership,
ReferenceCounting style) const {
switch (style) {
case ReferenceCounting::Native:
#define NEVER_LOADABLE_CHECKED_REF_STORAGE(Name, ...) \
if (ownership == ReferenceOwnership::Name) \
break;
#include "swift/AST/ReferenceStorage.def"
if (ObjCInterop)
break;
return getHeapObjectExtraInhabitantCount(*this);
case ReferenceCounting::Block:
case ReferenceCounting::ObjC:
case ReferenceCounting::Unknown:
break;
case ReferenceCounting::Bridge:
case ReferenceCounting::Error:
llvm_unreachable("Unsupported reference-counting style");
}
// The default behavior uses pointer semantics, therefore null is the only
// extra inhabitant allowed.
return 1;
}
SpareBitVector IRGenModule::getReferenceStorageSpareBits(
ReferenceOwnership ownership,
ReferenceCounting style) const {
// We have to be conservative (even with native reference-counting) in order
// to interoperate with code that might be working more generically with the
// memory/type.
switch (style) {
case ReferenceCounting::Native:
#define NEVER_LOADABLE_CHECKED_REF_STORAGE(Name, ...) \
if (ownership == ReferenceOwnership::Name) \
break;
#include "swift/AST/ReferenceStorage.def"
if (ObjCInterop)
break;
return getHeapObjectSpareBits();
case ReferenceCounting::Block:
case ReferenceCounting::ObjC:
case ReferenceCounting::Unknown:
break;
case ReferenceCounting::Bridge:
case ReferenceCounting::Error:
llvm_unreachable("Unsupported reference-counting style");
}
// The default behavior uses pointer semantics.
return SpareBitVector::getConstant(getPointerSize().getValueInBits(), false);
}
APInt IRGenModule::getReferenceStorageExtraInhabitantValue(unsigned bits,
unsigned index,
ReferenceOwnership ownership,
ReferenceCounting style) const {
// We have to be conservative (even with native reference-counting) in order
// to interoperate with code that might be working more generically with the
// memory/type.
switch (style) {
case ReferenceCounting::Native:
#define NEVER_LOADABLE_CHECKED_REF_STORAGE(Name, ...) \
if (ownership == ReferenceOwnership::Name) \
break;
#include "swift/AST/ReferenceStorage.def"
if (ObjCInterop)
break;
return getHeapObjectFixedExtraInhabitantValue(*this, bits, index, 0);
case ReferenceCounting::Block:
case ReferenceCounting::ObjC:
case ReferenceCounting::Unknown:
break;
case ReferenceCounting::Bridge:
case ReferenceCounting::Error:
llvm_unreachable("Unsupported reference-counting style");
}
// The default behavior allows for only one legal extra inhabitant, therefore
// this must be the null pattern.
assert(index == 0);
return APInt(bits, 0);
}
APInt IRGenModule::getReferenceStorageExtraInhabitantMask(
ReferenceOwnership ownership,
ReferenceCounting style) const {
switch (style) {
case ReferenceCounting::Native:
case ReferenceCounting::Block:
case ReferenceCounting::ObjC:
case ReferenceCounting::Unknown:
break;
case ReferenceCounting::Bridge:
case ReferenceCounting::Error:
llvm_unreachable("Unsupported reference-counting style");
}
return APInt::getAllOnesValue(getPointerSize().getValueInBits());
}
llvm::Value *IRGenFunction::getReferenceStorageExtraInhabitantIndex(Address src,
ReferenceOwnership ownership,
ReferenceCounting style) {
switch (style) {
case ReferenceCounting::Native:
if (IGM.ObjCInterop)
break;
return getHeapObjectExtraInhabitantIndex(*this, src);
case ReferenceCounting::Block:
case ReferenceCounting::ObjC:
case ReferenceCounting::Unknown:
break;
case ReferenceCounting::Bridge:
case ReferenceCounting::Error:
llvm_unreachable("Unsupported reference-counting style");
}
// The default behavior allows for only one legal extra inhabitant, therefore
// this must be the null pattern.
auto PtrTy =
#define CHECKED_REF_STORAGE(Name, ...) \
ownership == ReferenceOwnership::Name ? IGM.Name##ReferencePtrTy :
#include "swift/AST/ReferenceStorage.def"
nullptr;
(void)PtrTy;
assert(src.getAddress()->getType() == PtrTy);
src = Builder.CreateStructGEP(src, 0, Size(0));
llvm::Value *ptr = Builder.CreateLoad(src);
llvm::Value *isNull = Builder.CreateIsNull(ptr);
llvm::Value *result =
Builder.CreateSelect(isNull, Builder.getInt32(0),
llvm::ConstantInt::getSigned(IGM.Int32Ty, -1));
return result;
}
void IRGenFunction::storeReferenceStorageExtraInhabitant(llvm::Value *index,
Address dest,
ReferenceOwnership ownership,
ReferenceCounting style) {
switch (style) {
case ReferenceCounting::Native:
if (IGM.ObjCInterop)
break;
return storeHeapObjectExtraInhabitant(*this, index, dest);
case ReferenceCounting::Block:
case ReferenceCounting::ObjC:
case ReferenceCounting::Unknown:
break;
case ReferenceCounting::Bridge:
case ReferenceCounting::Error:
llvm_unreachable("Unsupported reference-counting style");
}
// The default behavior allows for only one legal extra inhabitant, therefore
// this must be the null pattern.
auto PtrTy =
#define CHECKED_REF_STORAGE(Name, ...) \
ownership == ReferenceOwnership::Name ? IGM.Name##ReferencePtrTy :
#include "swift/AST/ReferenceStorage.def"
nullptr;
(void)PtrTy;
assert(dest.getAddress()->getType() == PtrTy);
dest = Builder.CreateStructGEP(dest, 0, Size(0));
llvm::Value *null = llvm::ConstantPointerNull::get(IGM.RefCountedPtrTy);
Builder.CreateStore(null, dest);
}
#define SOMETIMES_UNKNOWN(Name) \
const TypeInfo * \
TypeConverter::create##Name##StorageType(llvm::Type *valueType, \
ReferenceCounting style, \
bool isOptional) { \
auto &&spareBits = IGM.getReferenceStorageSpareBits( \
ReferenceOwnership::Name, style); \
switch (style) { \
case ReferenceCounting::Native: \
return new Native##Name##ReferenceTypeInfo(valueType, \
IGM.Name##ReferencePtrTy->getElementType(), \
IGM.getPointerSize(), \
IGM.getPointerAlignment(), \
std::move(spareBits), \
isOptional); \
case ReferenceCounting::ObjC: \
case ReferenceCounting::Block: \
case ReferenceCounting::Unknown: \
return new Unknown##Name##ReferenceTypeInfo(valueType, \
IGM.Name##ReferencePtrTy->getElementType(), \
IGM.getPointerSize(), \
IGM.getPointerAlignment(), \
std::move(spareBits), \
isOptional); \
case ReferenceCounting::Bridge: \
case ReferenceCounting::Error: \
llvm_unreachable("not supported!"); \
} \
llvm_unreachable("bad reference-counting style"); \
}
#define ALWAYS_NATIVE(Name) \
const TypeInfo * \
TypeConverter::create##Name##StorageType(llvm::Type *valueType, \
ReferenceCounting style, \
bool isOptional) { \
assert(style == ReferenceCounting::Native); \
auto &&spareBits = IGM.getReferenceStorageSpareBits( \
ReferenceOwnership::Name, \
ReferenceCounting::Native); \
return new Native##Name##ReferenceTypeInfo(valueType, \
IGM.Name##ReferencePtrTy->getElementType(), \
IGM.getPointerSize(), \
IGM.getPointerAlignment(), \
std::move(spareBits), \
isOptional); \
}
// Always native versus "sometimes unknown" reference storage type policy:
SOMETIMES_UNKNOWN(Weak)
SOMETIMES_UNKNOWN(Unowned)
#undef SOMETIMES_UNKNOWN
#undef ALWAYS_NATIVE
#define CHECKED_REF_STORAGE(Name, ...) \
static_assert(&TypeConverter::create##Name##StorageType != nullptr, \
"Missing reference storage type converter helper constructor");
#define UNCHECKED_REF_STORAGE(Name, ...) \
const TypeInfo * \
TypeConverter::create##Name##StorageType(llvm::Type *valueType, \
ReferenceCounting style, \
bool isOptional) { \
(void)style; /* unused */ \
return new Name##ReferenceTypeInfo(valueType, \
IGM.getHeapObjectSpareBits(), \
IGM.getPointerSize(), \
IGM.getPointerAlignment(), \
isOptional); \
}
#include "swift/AST/ReferenceStorage.def"
/// Does the given value superficially not require reference-counting?
static bool doesNotRequireRefCounting(llvm::Value *value) {
// Constants never require reference-counting.
return isa<llvm::ConstantPointerNull>(value);
}
static llvm::FunctionType *getTypeOfFunction(llvm::Constant *fn) {
return cast<llvm::FunctionType>(fn->getType()->getPointerElementType());
}
/// Emit a unary call to perform a ref-counting operation.
///
/// \param fn - expected signature 'void (T)' or 'T (T)'
static void emitUnaryRefCountCall(IRGenFunction &IGF,
llvm::Constant *fn,
llvm::Value *value) {
auto cc = IGF.IGM.DefaultCC;
auto fun = dyn_cast<llvm::Function>(fn);
if (fun)
cc = fun->getCallingConv();
// Instead of casting the input, we cast the function type.
// This tends to produce less IR, but might be evil.
auto origFnType = getTypeOfFunction(fn);
if (value->getType() != origFnType->getParamType(0)) {
auto resultTy = origFnType->getReturnType() == IGF.IGM.VoidTy
? IGF.IGM.VoidTy
: value->getType();
llvm::FunctionType *fnType =
llvm::FunctionType::get(resultTy, value->getType(), false);
fn = llvm::ConstantExpr::getBitCast(fn, fnType->getPointerTo());
}
// Emit the call.
llvm::CallInst *call = IGF.Builder.CreateCall(fn, value);
if (fun && fun->hasParamAttribute(0, llvm::Attribute::Returned))
call->addParamAttr(0, llvm::Attribute::Returned);
call->setCallingConv(cc);
call->setDoesNotThrow();
}
/// Emit a copy-like call to perform a ref-counting operation.
///
/// \param fn - expected signature 'void (T, T)' or 'T (T, T)'
static void emitCopyLikeCall(IRGenFunction &IGF,
llvm::Constant *fn,
llvm::Value *dest,
llvm::Value *src) {
assert(dest->getType() == src->getType() &&
"type mismatch in binary refcounting operation");
auto cc = IGF.IGM.DefaultCC;
auto fun = dyn_cast<llvm::Function>(fn);
if (fun)
cc = fun->getCallingConv();
// Instead of casting the inputs, we cast the function type.
// This tends to produce less IR, but might be evil.
auto origFnType = getTypeOfFunction(fn);
if (dest->getType() != origFnType->getParamType(0)) {
llvm::Type *paramTypes[] = { dest->getType(), dest->getType() };
auto resultTy = origFnType->getReturnType() == IGF.IGM.VoidTy
? IGF.IGM.VoidTy
: dest->getType();
llvm::FunctionType *fnType =
llvm::FunctionType::get(resultTy, paramTypes, false);
fn = llvm::ConstantExpr::getBitCast(fn, fnType->getPointerTo());
}
// Emit the call.
llvm::CallInst *call = IGF.Builder.CreateCall(fn, {dest, src});
if (fun && fun->hasParamAttribute(0, llvm::Attribute::Returned))
call->addParamAttr(0, llvm::Attribute::Returned);
call->setCallingConv(cc);
call->setDoesNotThrow();
}
/// Emit a call to a function with a loadWeak-like signature.
///
/// \param fn - expected signature 'T (Weak*)'
static llvm::Value *emitLoadWeakLikeCall(IRGenFunction &IGF,
llvm::Constant *fn,
llvm::Value *addr,
llvm::Type *resultType) {
assert((addr->getType() == IGF.IGM.WeakReferencePtrTy ||
addr->getType() == IGF.IGM.UnownedReferencePtrTy) &&
"address is not of a weak or unowned reference");
auto cc = IGF.IGM.DefaultCC;
if (auto fun = dyn_cast<llvm::Function>(fn))
cc = fun->getCallingConv();
// Instead of casting the output, we cast the function type.
// This tends to produce less IR, but might be evil.
if (resultType != getTypeOfFunction(fn)->getReturnType()) {
llvm::Type *paramTypes[] = { addr->getType() };
llvm::FunctionType *fnType =
llvm::FunctionType::get(resultType, paramTypes, false);
fn = llvm::ConstantExpr::getBitCast(fn, fnType->getPointerTo());
}
// Emit the call.
llvm::CallInst *call = IGF.Builder.CreateCall(fn, addr);
call->setCallingConv(cc);
call->setDoesNotThrow();
return call;
}
/// Emit a call to a function with a storeWeak-like signature.
///
/// \param fn - expected signature 'void (Weak*, T)' or 'Weak* (Weak*, T)'
static void emitStoreWeakLikeCall(IRGenFunction &IGF,
llvm::Constant *fn,
llvm::Value *addr,
llvm::Value *value) {
assert((addr->getType() == IGF.IGM.WeakReferencePtrTy ||
addr->getType() == IGF.IGM.UnownedReferencePtrTy) &&
"address is not of a weak or unowned reference");
auto cc = IGF.IGM.DefaultCC;
auto fun = dyn_cast<llvm::Function>(fn);
if (fun)
cc = fun->getCallingConv();
// Instead of casting the inputs, we cast the function type.
// This tends to produce less IR, but might be evil.
auto origFnType = getTypeOfFunction(fn);
if (value->getType() != origFnType->getParamType(1)) {
llvm::Type *paramTypes[] = { addr->getType(), value->getType() };
auto resultTy = origFnType->getReturnType() == IGF.IGM.VoidTy
? IGF.IGM.VoidTy
: addr->getType();
llvm::FunctionType *fnType =
llvm::FunctionType::get(resultTy, paramTypes, false);
fn = llvm::ConstantExpr::getBitCast(fn, fnType->getPointerTo());
}
// Emit the call.
llvm::CallInst *call = IGF.Builder.CreateCall(fn, {addr, value});
if (fun && fun->hasParamAttribute(0, llvm::Attribute::Returned))
call->addParamAttr(0, llvm::Attribute::Returned);
call->setCallingConv(cc);
call->setDoesNotThrow();
}
/// Emit a call to swift_retain.
void IRGenFunction::emitNativeStrongRetain(llvm::Value *value,
Atomicity atomicity) {
if (doesNotRequireRefCounting(value))
return;
// Make sure the input pointer is the right type.
if (value->getType() != IGM.RefCountedPtrTy)
value = Builder.CreateBitCast(value, IGM.RefCountedPtrTy);
// Emit the call.
llvm::CallInst *call = Builder.CreateCall(
(atomicity == Atomicity::Atomic) ? IGM.getNativeStrongRetainFn()
: IGM.getNativeNonAtomicStrongRetainFn(),
value);
call->setDoesNotThrow();
call->addParamAttr(0, llvm::Attribute::Returned);
}
/// Emit a store of a live value to the given retaining variable.
void IRGenFunction::emitNativeStrongAssign(llvm::Value *newValue,
Address address) {
// Pull the old value out of the address.
llvm::Value *oldValue = Builder.CreateLoad(address);
// We assume the new value is already retained.
Builder.CreateStore(newValue, address);
// Release the old value.
emitNativeStrongRelease(oldValue, getDefaultAtomicity());
}
/// Emit an initialize of a live value to the given retaining variable.
void IRGenFunction::emitNativeStrongInit(llvm::Value *newValue,
Address address) {
// We assume the new value is already retained.
Builder.CreateStore(newValue, address);
}
/// Emit a release of a live value with the given refcounting implementation.
void IRGenFunction::emitStrongRelease(llvm::Value *value,
ReferenceCounting refcounting,
Atomicity atomicity) {
switch (refcounting) {
case ReferenceCounting::Native:
return emitNativeStrongRelease(value, atomicity);
case ReferenceCounting::ObjC:
return emitObjCStrongRelease(value);
case ReferenceCounting::Block:
return emitBlockRelease(value);
case ReferenceCounting::Unknown:
return emitUnknownStrongRelease(value, atomicity);
case ReferenceCounting::Bridge:
return emitBridgeStrongRelease(value, atomicity);
case ReferenceCounting::Error: