-
Notifications
You must be signed in to change notification settings - Fork 10.4k
/
Copy pathSILGenPoly.cpp
1540 lines (1346 loc) · 62.2 KB
/
SILGenPoly.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
//===--- SILGenPoly.cpp - Polymorphic Abstraction Difference --------------===//
//
// 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
//
//===----------------------------------------------------------------------===//
//
// Routines for manipulating and translating between polymorphic
// abstraction patterns.
//
// The representation of values in Swift can vary according to how
// their type is abstracted: which is to say, according to the pattern
// of opaque type variables within their type. The main motivation
// here is performance: it would be far easier for types to adopt a
// single representation regardless of their abstraction, but this
// would force Swift to adopt a very inefficient representation for
// abstractable values.
//
// For example, consider the comparison function on Int:
// func <(lhs : Int, rhs : Int) -> Bool
//
// This function can be used as an opaque value of type
// (Int,Int)->Bool. An optimal representation of values of that type
// (ignoring context parameters for the moment) would be a pointer to
// a function that takes these two arguments directly in registers and
// returns the result directly in a register.
//
// (It's important to remember throughout this discussion that we're
// talking about abstract values. There's absolutely nothing that
// requires direct uses of the function to follow the same conventions
// as abstract uses! A direct use of a declaration --- even one that
// implies an indirect call, like a class's instance method ---
// provides a concrete specification for exactly how to interact with
// value.)
//
// However, that representation is problematic in the presence of
// generics. This function could be passed off to any of the following
// generic functions:
// func foo<T>(f : (T, Int) -> Bool)
// func bar<U,V>(f : (U, V) -> Bool)
// func baz<W>(f : (Int, Int) -> W)
//
// These generic functions all need to be able to call 'f'. But in
// Swift's implementation model, these functions don't have to be
// instantiated for different parameter types, which means that (e.g.)
// the same 'baz' implementation needs to also be able to work when
// W=String. But the optimal way to pass an Int to a function might
// well be different from the optimal way to pass a String.
//
// And this runs in both directions: a generic function might return
// a function that the caller would like to use as an (Int,Int)->Bool:
// func getFalseFunction<T>() -> (T,T)->Bool
//
// There are three ways we can deal with this:
//
// 1. Give all types in Swift a common representation. The generic
// implementation can work with both W=String and W=Int because
// both of those types have the same (direct) storage representation.
// That's pretty clearly not an acceptable sacrifice.
//
// 2. Adopt a most-general representation of function types that is
// used for opaque values; for example, all parameters and results
// could be passed indirectly. Concrete values must be coerced to
// this representation when made abstract. Unfortunately, there
// are a lot of obvious situations where this is sub-optimal:
// for example, in totally non-generic code that just passes around
// a value of type (Int,Int)->Bool. It's particularly bad because
// Swift functions take multiple arguments as just a tuple, and that
// tuple is usually abstractable: e.g., '<' above could also be
// passed to this:
// func fred<T>(f : T -> Bool)
//
// 3. Permit the representation of values to vary by abstraction.
// Values require coercion when changing abstraction patterns.
// For example, the argument to 'fred' would be expected to return
// its Bool result directly but take a single T parameter indirectly.
// When '<' is passed to this, what must actually be passed is a
// thunk that expects a tuple of type (Int,Int) to be stored at
// the input address.
//
// There is one major risk with (3): naively implemented, a single
// function value which undergoes many coercions could build up a
// linear number of re-abstraction thunks. However, this can be
// solved dynamically by applying thunks with a runtime functon that
// can recognize and bypass its own previous handiwork.
//
// There is one major exception to what sub-expressions in a type
// expression can be abstracted with type variables: a type substitution
// must always be materializable. For example:
// func f(inout Int, Int) -> Bool
// 'f' cannot be passed to 'foo' above: T=inout Int is not a legal
// substitution. Nor can it be passed to 'fred'.
//
// In general, abstraction patterns are derived from some explicit
// type expression, such as the written type of a variable or
// parameter. This works whenever the expression directly provides
// structure for the type in question; for example, when the original
// type is (T,Int)->Bool and we are working with an (Int,Int)->Bool
// substitution. However, it is inadequate when the expression does
// not provide structure at the appropriate level, i.e. when that
// level is substituted in: when the original type is merely T. In
// these cases, we must devolve to a representation which all legal
// substitutors will agree upon. In general, this is the
// representation of the type which replaces all materializable
// sub-expressions with a fresh type variable.
//
// For example, when applying the substitution
// T=(Int,Int)->Bool
// values of T are abstracted as if they were of type U->V, i.e.
// taking one indirect parameter and returning one indirect result.
//
// But under the substitution
// T=(inout Int,Int)->Bool
// values of T are abstracted as if they were of type (inout U,V)->W,
// i.e. taking one parameter inout, another indirectly, and returning
// one indirect result.
//
// We generally pass around an original, unsubstituted type as the
// abstraction pattern. The exact archetypes in this type are
// irrelevant; only whether or not a position is filled by an
// archetype matters.
//
//===----------------------------------------------------------------------===//
#include "SILGen.h"
#include "Scope.h"
#include "swift/Basic/Fallthrough.h"
#include "swift/AST/AST.h"
#include "swift/AST/Decl.h"
#include "swift/AST/Types.h"
#include "swift/SIL/PrettyStackTrace.h"
#include "swift/SIL/SILArgument.h"
#include "swift/SIL/TypeLowering.h"
#include "Initialization.h"
#include "LValue.h"
#include "RValue.h"
using namespace swift;
using namespace Lowering;
namespace {
/// An abstract class for transforming first-class SIL values.
class Transform {
protected:
SILGenFunction &SGF;
SILLocation Loc;
public:
Transform(SILGenFunction &SGF, SILLocation loc) : SGF(SGF), Loc(loc) {}
virtual ~Transform() = default;
/// Transform an arbitrary value.
ManagedValue transform(ManagedValue input,
AbstractionPattern origType,
CanType substType,
SGFContext ctxt);
/// Transform a metatype value.
virtual ManagedValue transformMetatype(ManagedValue fn,
AbstractionPattern origType,
CanAnyMetatypeType substType) = 0;
/// Transform a tuple value.
ManagedValue transformTuple(ManagedValue input,
AbstractionPattern origType,
CanTupleType substType,
SGFContext ctxt);
/// Transform a function value.
virtual ManagedValue transformFunction(ManagedValue fn,
AbstractionPattern origType,
CanAnyFunctionType substType) = 0;
/// Return the expected type of a lowered value.
virtual const TypeLowering &getExpectedTypeLowering(AbstractionPattern origType,
CanType substType) = 0;
};
};
/// Apply this transformation to an arbitrary value.
ManagedValue Transform::transform(ManagedValue v,
AbstractionPattern origFormalType,
CanType substFormalType,
SGFContext ctxt) {
// Transformable values are:
// - functions
if (auto substFnType = dyn_cast<AnyFunctionType>(substFormalType)) {
return transformFunction(v, origFormalType, substFnType);
}
// - tuples of transformable values
if (auto substTupleType = dyn_cast<TupleType>(substFormalType)) {
return transformTuple(v, origFormalType, substTupleType, ctxt);
}
// - metatypes
if (auto substMetaType = dyn_cast<AnyMetatypeType>(substFormalType)) {
return transformMetatype(v, origFormalType, substMetaType);
}
// Nothing else.
return v;
}
/// Explode a managed tuple into a bunch of managed elements.
///
/// If the tuple is in memory, the result elements will also be in
/// memory.
typedef std::pair<ManagedValue, const TypeLowering *> ManagedValueAndType;
static void explodeTuple(SILGenFunction &gen,
SILLocation loc,
ManagedValue managedTuple,
SmallVectorImpl<ManagedValueAndType> &out) {
// None of the operations we do here can fail, so we can atomically
// disable the tuple's cleanup and then create cleanups for all the
// elements.
SILValue tuple = managedTuple.forward(gen);
auto tupleSILType = tuple.getType();
auto tupleType = tupleSILType.castTo<TupleType>();
out.reserve(tupleType->getNumElements());
for (auto index : indices(tupleType.getElementTypes())) {
// We're starting with a SIL-lowered tuple type, so the elements
// must also all be SIL-lowered.
SILType eltType = tupleSILType.getTupleElementType(index);
auto &eltTL = gen.getTypeLowering(eltType);
ManagedValue elt;
if (tupleSILType.isAddress()) {
auto addr = gen.B.createTupleElementAddr(loc, tuple, index, eltType);
elt = gen.emitManagedBufferWithCleanup(addr, eltTL);
} else {
auto value = gen.B.createTupleExtract(loc, tuple, index, eltType);
elt = gen.emitManagedRValueWithCleanup(value, eltTL);
}
out.push_back(ManagedValueAndType(elt, &eltTL));
}
}
static ManagedValue emitManagedLoad(SILGenFunction &gen, SILLocation loc,
ManagedValue addr,
const TypeLowering &addrTL) {
auto loadedValue = gen.B.createLoad(loc, addr.forward(gen));
return gen.emitManagedRValueWithCleanup(loadedValue, addrTL);
}
/// Apply this transformation to all the elements of a tuple value,
/// which just entails mapping over each of its component elements.
ManagedValue Transform::transformTuple(ManagedValue inputTuple,
AbstractionPattern origFormalType,
CanTupleType substFormalType,
SGFContext ctxt) {
const TypeLowering &outputTL =
getExpectedTypeLowering(origFormalType, substFormalType);
assert(outputTL.isAddressOnly() == inputTuple.getType().isAddress() &&
"expected loadable inputs to have been loaded");
// If there's no representation difference, we're done.
if (outputTL.getLoweredType() == inputTuple.getType())
return inputTuple;
assert(origFormalType.matchesTuple(substFormalType));
auto inputType = inputTuple.getType().castTo<TupleType>();
assert(substFormalType->getNumElements() == inputType->getNumElements());
// If the tuple is address only, we need to do the operation in memory.
SILValue outputAddr;
if (outputTL.isAddressOnly())
outputAddr = SGF.getBufferForExprResult(Loc, outputTL.getLoweredType(),
ctxt);
// Explode the tuple into individual managed values.
SmallVector<ManagedValueAndType, 4> inputElts;
explodeTuple(SGF, Loc, inputTuple, inputElts);
// Track all the managed elements whether or not we're actually
// emitting to an address, just so that we can disable them ater.
SmallVector<ManagedValue, 4> outputElts;
for (auto index : indices(inputType->getElementTypes())) {
auto &inputEltTL = *inputElts[index].second;
ManagedValue inputElt = inputElts[index].first;
if (inputElt.getType().isAddress() && !inputEltTL.isAddressOnly()) {
inputElt = emitManagedLoad(SGF, Loc, inputElt, inputEltTL);
}
auto origEltFormalType = origFormalType.getTupleElementType(index);
auto substEltFormalType = substFormalType.getElementType(index);
// If we're emitting to memory, project out this element in the
// destination buffer, then wrap that in an Initialization to
// track the cleanup.
Optional<TemporaryInitialization> outputEltTemp;
if (outputAddr) {
SILValue outputEltAddr =
SGF.B.createTupleElementAddr(Loc, outputAddr, index);
auto &outputEltTL = SGF.getTypeLowering(outputEltAddr.getType());
assert(outputEltTL.isAddressOnly() == inputEltTL.isAddressOnly());
auto cleanup =
SGF.enterDormantTemporaryCleanup(outputEltAddr, outputEltTL);
outputEltTemp.emplace(outputEltAddr, cleanup);
}
SGFContext eltCtxt =
(outputEltTemp ? SGFContext(&outputEltTemp.getValue()) : SGFContext());
auto outputElt = transform(inputElt, origEltFormalType, substEltFormalType,
eltCtxt);
// If we're not emitting to memory, remember this element for
// later assembly into a tuple.
if (!outputEltTemp) {
assert(outputElt);
assert(!inputEltTL.isAddressOnly());
outputElts.push_back(outputElt);
continue;
}
// Otherwise, make sure we emit into the slot.
auto &temp = outputEltTemp.getValue();
auto outputEltAddr = temp.getManagedAddress();
// That might involve storing directly.
if (outputElt) {
outputElt.forwardInto(SGF, Loc, outputEltAddr.getValue());
temp.finishInitialization(SGF);
}
outputElts.push_back(outputEltAddr);
}
// Okay, disable all the individual element cleanups and collect
// the values for a potential tuple aggregate.
SmallVector<SILValue, 4> outputEltValues;
for (auto outputElt : outputElts) {
SILValue value = outputElt.forward(SGF);
if (!outputAddr) outputEltValues.push_back(value);
}
// If we're emitting to an address, just manage that.
if (outputAddr)
return SGF.manageBufferForExprResult(outputAddr, outputTL, ctxt);
// Otherwise, assemble the tuple value and manage that.
auto outputTuple =
SGF.B.createTuple(Loc, outputTL.getLoweredType(), outputEltValues);
return SGF.emitManagedRValueWithCleanup(outputTuple, outputTL);
}
static ManagedValue manageParam(SILGenFunction &gen,
SILLocation loc,
SILValue paramValue,
SILParameterInfo info) {
switch (info.getConvention()) {
case ParameterConvention::Direct_Unowned:
case ParameterConvention::Direct_Guaranteed:
gen.getTypeLowering(paramValue.getType())
.emitRetainValue(gen.B, loc, paramValue);
SWIFT_FALLTHROUGH;
case ParameterConvention::Direct_Owned:
return gen.emitManagedRValueWithCleanup(paramValue);
case ParameterConvention::Indirect_Inout:
return ManagedValue::forLValue(paramValue);
case ParameterConvention::Indirect_In:
return gen.emitManagedBufferWithCleanup(paramValue);
case ParameterConvention::Indirect_Out:
llvm_unreachable("shouldn't be handled out-parameters here");
}
llvm_unreachable("bad parameter convention");
}
static void collectParams(SILGenFunction &gen,
SILLocation loc,
SmallVectorImpl<ManagedValue> ¶ms) {
auto paramTypes =
gen.F.getLoweredFunctionType()->getInterfaceParametersWithoutIndirectResult();
for (auto param : paramTypes) {
auto paramTy = gen.F.mapTypeIntoContext(param.getSILType());
auto paramValue = new (gen.SGM.M) SILArgument(paramTy,
gen.F.begin());
params.push_back(manageParam(gen, loc, paramValue, param));
}
}
enum class TranslationKind {
Generalize, OrigToSubst, SubstToOrig
};
/// Flip the direction of translation.
static TranslationKind getInverse(TranslationKind kind) {
switch (kind) {
case TranslationKind::Generalize:
// This is a bit odd?
return TranslationKind::SubstToOrig;
case TranslationKind::OrigToSubst:
return TranslationKind::SubstToOrig;
case TranslationKind::SubstToOrig:
return TranslationKind::OrigToSubst;
}
llvm_unreachable("bad translation kind");
}
static bool isOutputSubstituted(TranslationKind kind) {
switch (kind) {
case TranslationKind::Generalize: return true;
case TranslationKind::OrigToSubst: return true;
case TranslationKind::SubstToOrig: return false;
}
llvm_unreachable("bad translation kind");
}
/// Primitively translate the given value.
static ManagedValue emitTranslatePrimitive(SILGenFunction &SGF,
SILLocation loc,
TranslationKind kind,
AbstractionPattern origType,
CanType substType,
ManagedValue input,
SGFContext context = SGFContext()) {
// Load if the result isn't address-only. All the translation routines
// expect this.
auto inputType = input.getType();
if (inputType.isAddress()) {
auto &inputTL = SGF.getTypeLowering(inputType);
if (!inputTL.isAddressOnly()) {
input = emitManagedLoad(SGF, loc, input, inputTL);
}
}
switch (kind) {
case TranslationKind::Generalize:
return SGF.emitGeneralizedValue(loc, input, origType, substType, context);
case TranslationKind::SubstToOrig:
return SGF.emitSubstToOrigValue(loc, input, origType, substType, context);
case TranslationKind::OrigToSubst:
return SGF.emitOrigToSubstValue(loc, input, origType, substType, context);
}
llvm_unreachable("bad translation kind");
}
/// Force a ManagedValue to be stored into a temporary initialization
/// if it wasn't emitted that way directly.
static void emitForceInto(SILGenFunction &SGF, SILLocation loc,
ManagedValue result, TemporaryInitialization &temp) {
if (!result) return;
result.forwardInto(SGF, loc, temp.getAddress());
temp.finishInitialization(SGF);
}
namespace {
class TranslateArguments {
SILGenFunction &SGF;
SILLocation Loc;
TranslationKind Kind;
ArrayRef<ManagedValue> Inputs;
SmallVectorImpl<ManagedValue> &Outputs;
ArrayRef<SILParameterInfo> OutputTypes;
public:
TranslateArguments(SILGenFunction &SGF, SILLocation loc,
TranslationKind kind,
ArrayRef<ManagedValue> inputs,
SmallVectorImpl<ManagedValue> &outputs,
ArrayRef<SILParameterInfo> outputTypes)
: SGF(SGF), Loc(loc), Kind(kind), Inputs(inputs), Outputs(outputs),
OutputTypes(outputTypes) {}
void translate(AbstractionPattern origType, CanType substType) {
// Tuples are exploded recursively.
if (isa<TupleType>(origType.getAsType())) {
return translateParallelExploded(origType, cast<TupleType>(substType));
}
if (auto substTuple = dyn_cast<TupleType>(substType)) {
if (!substTuple->isMaterializable())
return translateParallelExploded(origType, substTuple);
return translateExplodedIndirect(origType, substTuple);
}
// Okay, we are now working with a single value turning into a
// single value.
auto input = claimNextInput();
auto outputType = claimNextOutputType();
translateSingle(origType, substType, input, outputType);
}
private:
/// Handle a tuple that has been exploded in both the input and
/// the output.
void translateParallelExploded(AbstractionPattern origType,
CanTupleType substType) {
assert(origType.matchesTuple(substType));
for (auto index : indices(substType.getElementTypes())) {
translate(origType.getTupleElementType(index),
substType.getElementType(index));
}
}
/// Handle a tuple that is exploded only in the substituted type.
void translateExplodedIndirect(AbstractionPattern origType,
CanTupleType substType) {
// It matters at this point whether we're translating into the
// substitution or out of it.
if (isOutputSubstituted(Kind)) {
return translateAndExplodeOutOf(origType, substType, claimNextInput());
}
auto output = claimNextOutputType();
auto &outputTL = SGF.getTypeLowering(output.getSILType());
auto temp = SGF.emitTemporary(Loc, outputTL);
translateAndImplodeInto(origType, substType, *temp.get());
Outputs.push_back(temp->getManagedAddress());
}
/// Given that a tuple value is being passed indirectly in the
/// input, explode it and translate the elements.
void translateAndExplodeOutOf(AbstractionPattern origTupleType,
CanTupleType substTupleType,
ManagedValue inputTupleAddr) {
SmallVector<ManagedValueAndType, 4> inputEltAddrs;
explodeTuple(SGF, Loc, inputTupleAddr, inputEltAddrs);
assert(inputEltAddrs.size() == substTupleType->getNumElements());
for (auto index : indices(substTupleType.getElementTypes())) {
auto origEltType = origTupleType.getTupleElementType(index);
auto substEltType = substTupleType.getElementType(index);
auto inputEltAddr = inputEltAddrs[index].first;
assert(inputEltAddr.getType().isAddress());
if (auto substEltTupleType = dyn_cast<TupleType>(substEltType)) {
translateAndExplodeOutOf(origEltType, substEltTupleType, inputEltAddr);
} else {
auto outputType = claimNextOutputType();
translateSingle(origEltType, substEltType, inputEltAddr, outputType);
}
}
}
/// Given that a tuple value is being passed indirectly in the
/// output, translate the elements and implode it.
void translateAndImplodeInto(AbstractionPattern origTupleType,
CanTupleType substTupleType,
TemporaryInitialization &tupleInit) {
SmallVector<CleanupHandle, 4> cleanups;
for (auto index : indices(substTupleType.getElementTypes())) {
auto origEltType = origTupleType.getTupleElementType(index);
auto substEltType = substTupleType.getElementType(index);
auto eltAddr =
SGF.B.createTupleElementAddr(Loc, tupleInit.getAddress(), index);
auto &outputEltTL = SGF.getTypeLowering(eltAddr->getType());
CleanupHandle eltCleanup =
SGF.enterDormantTemporaryCleanup(eltAddr, outputEltTL);
if (eltCleanup.isValid()) cleanups.push_back(eltCleanup);
TemporaryInitialization eltInit(eltAddr, eltCleanup);
if (auto substEltTupleType = dyn_cast<TupleType>(substEltType)) {
translateAndImplodeInto(origEltType, substEltTupleType, eltInit);
} else {
// Otherwise, we come from a single value.
auto input = claimNextInput();
translateSingleInto(origEltType, substEltType, input, eltInit);
}
}
// Deactivate all the element cleanups and activate the tuple cleanup.
for (auto cleanup : cleanups)
SGF.Cleanups.setCleanupState(cleanup, CleanupState::Dead);
tupleInit.finishInitialization(SGF);
}
/// Translate a single value and add it as an output.
void translateSingle(AbstractionPattern origType, CanType substType,
ManagedValue input, SILParameterInfo outputType) {
// Easy case: we want to pass exactly this value.
if (input.getType() == outputType.getSILType()) {
Outputs.push_back(input);
return;
}
// Direct translation is relatively easy.
if (!outputType.isIndirect()) {
auto output = translatePrimitive(origType, substType, input);
assert(output.getType() == outputType.getSILType());
Outputs.push_back(output);
return;
}
// Otherwise, we're using one of the indirect conventions.
// If it's inout, we need writeback.
if (outputType.isIndirectInOut()) {
llvm::errs() << "inout writeback in abstraction difference thunk "
"not yet implemented\n";
llvm::errs() << "input value "; input.getValue().dump();
llvm::errs() << "output type " << outputType.getSILType() << "\n";
abort();
}
// Otherwise, we need to translate into a temporary.
assert(outputType.getConvention() == ParameterConvention::Indirect_In);
auto &outputTL = SGF.getTypeLowering(outputType.getSILType());
auto temp = SGF.emitTemporary(Loc, outputTL);
translateSingleInto(origType, substType, input, *temp.get());
Outputs.push_back(temp->getManagedAddress());
}
/// Translate a single value and initialize the given temporary with it.
void translateSingleInto(AbstractionPattern origType, CanType substType,
ManagedValue input,
TemporaryInitialization &temp) {
auto output = translatePrimitive(origType, substType, input,
SGFContext(&temp));
forceInto(output, temp);
}
/// Apply primitive translation to the given value.
ManagedValue translatePrimitive(AbstractionPattern origType,
CanType substType, ManagedValue input,
SGFContext context = SGFContext()) {
return emitTranslatePrimitive(SGF, Loc, Kind, origType, substType,
input, context);
}
/// Force the given result into the given initialization.
void forceInto(ManagedValue result, TemporaryInitialization &temp) {
emitForceInto(SGF, Loc, result, temp);
}
ManagedValue claimNextInput() {
assert(!Inputs.empty());
auto next = Inputs.front();
Inputs = Inputs.slice(1);
return next;
}
SILParameterInfo claimNextOutputType() {
assert(!OutputTypes.empty());
auto next = OutputTypes.front();
OutputTypes = OutputTypes.slice(1);
return next;
}
};
}
/// Forward arguments according to a function type's ownership conventions.
static void forwardFunctionArguments(SILGenFunction &gen,
SILLocation loc,
CanSILFunctionType fTy,
ArrayRef<ManagedValue> managedArgs,
SmallVectorImpl<SILValue> &forwardedArgs) {
auto argTypes = fTy->getInterfaceParametersWithoutIndirectResult();
for (auto index : indices(managedArgs)) {
auto &arg = managedArgs[index];
auto argTy = argTypes[index];
forwardedArgs.push_back(argTy.isConsumed() ? arg.forward(gen)
: arg.getValue());
}
}
/// Create a temporary result buffer, reuse an existing result address, or
/// return null, based on the calling convention of a function type.
static SILValue getThunkInnerResultAddr(SILGenFunction &gen,
SILLocation loc,
CanSILFunctionType fTy,
SILValue outerResultAddr) {
if (fTy->hasIndirectResult()) {
auto resultType = fTy->getIndirectInterfaceResult().getSILType();
resultType = gen.F.mapTypeIntoContext(resultType);
// Re-use the original result if possible.
if (outerResultAddr && outerResultAddr.getType() == resultType)
return outerResultAddr;
else
return gen.emitTemporaryAllocation(loc, resultType);
}
return {};
}
/// Return the result of a function application as the result from a thunk.
static SILValue getThunkResult(SILGenFunction &gen,
SILLocation loc,
TranslationKind kind,
CanSILFunctionType fTy,
AbstractionPattern origResultType,
CanType substResultType,
SILValue innerResultValue,
SILValue innerResultAddr,
SILValue outerResultAddr) {
// Convert the direct result to +1 if necessary.
auto resultTy = gen.F.mapTypeIntoContext(fTy->getSemanticInterfaceResultSILType());
auto &innerResultTL = gen.getTypeLowering(resultTy);
if (!fTy->hasIndirectResult()) {
switch (fTy->getInterfaceResult().getConvention()) {
case ResultConvention::Owned:
break;
case ResultConvention::Autoreleased:
innerResultValue =
gen.B.createStrongRetainAutoreleased(loc, innerResultValue);
break;
case ResultConvention::Unowned:
innerResultTL.emitRetainValue(gen.B, loc, innerResultValue);
break;
}
}
// Control the result value. The real result value is in the
// indirect output if it exists.
ManagedValue innerResult;
if (innerResultAddr) {
innerResult = gen.emitManagedBufferWithCleanup(innerResultAddr,
innerResultTL);
} else {
innerResult = gen.emitManagedRValueWithCleanup(innerResultValue,
innerResultTL);
}
if (outerResultAddr) {
// If we emitted directly, there's nothing more to do.
// Let the caller claim the result.
if (innerResultAddr == outerResultAddr) {
innerResult.forwardCleanup(gen);
innerResult = {};
// Otherwise we'll have to copy over.
} else {
TemporaryInitialization init(outerResultAddr, CleanupHandle::invalid());
auto translated = emitTranslatePrimitive(gen, loc, kind, origResultType,
substResultType, innerResult,
/*emitInto*/ SGFContext(&init));
emitForceInto(gen, loc, translated, init);
}
// Use the () from the call as the result of the outer function if
// it's available.
if (innerResultAddr) {
return innerResultValue;
} else {
auto voidTy = gen.SGM.Types.getEmptyTupleType();
return gen.B.createTuple(loc, voidTy, {});
}
} else {
auto translated = emitTranslatePrimitive(gen, loc, kind, origResultType,
substResultType, innerResult);
return translated.forward(gen);
}
}
/// Build the body of a transformation thunk.
static void buildThunkBody(SILGenFunction &gen, SILLocation loc,
TranslationKind kind,
AbstractionPattern origFormalType,
CanAnyFunctionType substFormalType) {
PrettyStackTraceSILFunction stackTrace("emitting reabstraction thunk in",
&gen.F);
auto thunkType = gen.F.getLoweredFunctionType();
FullExpr scope(gen.Cleanups, CleanupLocation::getCleanupLocation(loc));
SILValue outerResultAddr;
if (thunkType->hasIndirectResult()) {
auto resultType = thunkType->getIndirectInterfaceResult().getSILType();
resultType = gen.F.mapTypeIntoContext(resultType);
outerResultAddr = new (gen.SGM.M) SILArgument(resultType, gen.F.begin());
}
SmallVector<ManagedValue, 8> params;
collectParams(gen, loc, params);
ManagedValue fnValue = params.pop_back_val();
auto fnType = fnValue.getType().castTo<SILFunctionType>();
assert(!fnType->isPolymorphic());
auto argTypes = fnType->getInterfaceParametersWithoutIndirectResult();
// Translate the argument values. Function parameters are
// contravariant: we want to switch the direction of transformation
// on them. For example, a subst-to-orig transformation of
// (Int,Int)->Int to (T,T)->T is one that should take an
// (Int,Int)->Int value and make it be abstracted like a (T,T)->T
// value. This must be done with a thunk. Within the thunk body,
// results need to be subst-to-orig translated (we receive an Int
// like a T and turn it into a normal Int), but the parameters need
// to be orig-to-subst translated (we receive an Int like normal,
// but we need to forward it like we would a T).
SmallVector<ManagedValue, 8> args;
TranslateArguments(gen, loc, getInverse(kind), params, args, argTypes)
.translate(origFormalType.getFunctionInputType(),
substFormalType.getInput());
SmallVector<SILValue, 8> argValues;
// Create an indirect result buffer if required.
SILValue innerResultAddr = getThunkInnerResultAddr(gen, loc,
fnType, outerResultAddr);
if (innerResultAddr)
argValues.push_back(innerResultAddr);
// Add the rest of the arguments.
forwardFunctionArguments(gen, loc, fnType, args, argValues);
SILValue innerResultValue =
gen.B.createApply(loc, fnValue.forward(gen),
/*substFnType*/ fnValue.getType(),
fnType->getInterfaceResult().getSILType(),
/*substitutions*/ {},
argValues);
// Translate the result value.
auto origResultType = origFormalType.getFunctionResultType();
auto substResultType = substFormalType.getResult();
SILValue outerResultValue = getThunkResult(gen, loc, kind, fnType,
origResultType, substResultType,
innerResultValue,
innerResultAddr,
outerResultAddr);
scope.pop();
gen.B.createReturn(loc, outerResultValue);
}
/// Build the type of a transformation thunk.
static CanSILFunctionType buildThunkType(SILGenFunction &gen,
ManagedValue fn,
CanSILFunctionType expectedType,
CanSILFunctionType &substFnType,
SmallVectorImpl<Substitution> &subs) {
auto sourceType = fn.getType().castTo<SILFunctionType>();
assert(!expectedType->isPolymorphic());
assert(!sourceType->isPolymorphic());
assert(!expectedType->isThin());
// Just use the generic signature from the context.
// This isn't necessarily optimal.
auto generics = gen.F.getContextGenericParams();
auto genericSig = gen.F.getLoweredFunctionType()->getGenericSignature();
if (generics) {
for (auto archetype : generics->getAllNestedArchetypes())
subs.push_back({ archetype, archetype, { }});
}
// Add the function type as the parameter.
SmallVector<SILParameterInfo, 4> params;
params.append(expectedType->getInterfaceParameters().begin(),
expectedType->getInterfaceParameters().end());
params.push_back({sourceType,
sourceType->isThin() ? ParameterConvention::Direct_Unowned
: DefaultThickCalleeConvention});
auto extInfo = expectedType->getExtInfo().withIsThin(true);
// Map the parameter and expected types out of context to get the interface
// type of the thunk.
SmallVector<SILParameterInfo, 4> interfaceParams;
interfaceParams.reserve(params.size());
auto &Types = gen.SGM.M.Types;
for (auto ¶m : params) {
interfaceParams.push_back(
SILParameterInfo(Types.getInterfaceTypeInContext(param.getType(), generics),
param.getConvention()));
}
auto interfaceResult = SILResultInfo(
Types.getInterfaceTypeInContext(expectedType->getInterfaceResult().getType(), generics),
expectedType->getInterfaceResult().getConvention());
// The type of the thunk function.
auto thunkType = SILFunctionType::get(genericSig, extInfo,
ParameterConvention::Direct_Unowned,
interfaceParams, interfaceResult,
gen.getASTContext());
// Define the substituted function type for partial_apply's purposes.
if (!generics) {
substFnType = thunkType;
} else {
substFnType = SILFunctionType::get(nullptr, extInfo,
ParameterConvention::Direct_Unowned,
params,
expectedType->getInterfaceResult(),
gen.getASTContext());
}
return thunkType;
}
/// Create a reabstraction thunk.
static ManagedValue createThunk(SILGenFunction &gen,
SILLocation loc,
TranslationKind kind,
ManagedValue fn,
AbstractionPattern origFormalType,
CanAnyFunctionType substFormalType,
const TypeLowering &expectedTL) {
auto expectedType = expectedTL.getLoweredType().castTo<SILFunctionType>();
// Declare the thunk.
SmallVector<Substitution, 4> substitutions;
CanSILFunctionType substFnType;
auto thunkType = buildThunkType(gen, fn, expectedType,
substFnType, substitutions);
auto thunk = gen.SGM.getOrCreateReabstractionThunk(loc,
gen.F.getContextGenericParams(),
thunkType,
fn.getType().castTo<SILFunctionType>(),
expectedType);
// Build it if necessary.
if (thunk->empty()) {
// Borrow the context archetypes from the enclosing function.
thunk->setContextGenericParams(gen.F.getContextGenericParams());
SILGenFunction thunkSGF(gen.SGM, *thunk);
buildThunkBody(thunkSGF, loc, kind, origFormalType, substFormalType);
}
// Create it in our current function.
auto thunkValue = gen.B.createFunctionRef(loc, thunk);
auto thunkedFn = gen.B.createPartialApply(loc, thunkValue,
SILType::getPrimitiveObjectType(substFnType),
substitutions, fn.forward(gen),
SILType::getPrimitiveObjectType(expectedType));
return gen.emitManagedRValueWithCleanup(thunkedFn, expectedTL);
}
static ManagedValue
emitGeneralizeFunctionWithThunk(SILGenFunction &gen,
SILLocation loc,
ManagedValue fn,
AbstractionPattern origFormalType,
CanAnyFunctionType substFormalType,
const TypeLowering &expectedTL) {
return createThunk(gen, loc, TranslationKind::Generalize, fn,
origFormalType, substFormalType, expectedTL);
}
ManagedValue
SILGenFunction::emitGeneralizedFunctionValue(SILLocation loc,
ManagedValue fn,
AbstractionPattern origFormalType,
CanAnyFunctionType substFormalType) {
assert(fn.getType().isObject() &&
"expected input to emitGeneralizedValue to be loaded");
auto &expectedTL = getTypeLowering(substFormalType);
auto expectedFnType = expectedTL.getLoweredType().castTo<SILFunctionType>();
auto fnType = fn.getType().castTo<SILFunctionType>();
assert(!expectedFnType->isThin() || fnType->isThin());
// If there's no abstraction difference, we're done.
if (fnType == expectedFnType) {
return fn;
}
// Any of these changes requires a conversion thunk.
if (fnType->getInterfaceResult() != expectedFnType->getInterfaceResult() ||
fnType->getInterfaceParameters() != expectedFnType->getInterfaceParameters() ||
(!fnType->isThin() &&
fnType->getCalleeConvention() != expectedFnType->getCalleeConvention()) ||
fnType->getAbstractCC() != expectedFnType->getAbstractCC()) {
assert(!expectedFnType->isThin() && "conversion thunk will not be thin!");
return emitGeneralizeFunctionWithThunk(*this, loc, fn,
origFormalType, substFormalType,
expectedTL);
}
// Otherwise, we should just have trivial-ish ExtInfo differences.
auto fnEI = fnType->getExtInfo();
auto expectedEI = expectedFnType->getExtInfo();
assert(fnEI != expectedEI && "unhandled difference in function types?");
assert(adjustFunctionType(fnType, expectedEI,
expectedFnType->getCalleeConvention())
== expectedFnType);
auto emitConversion = [&](SILFunctionType::ExtInfo newEI,
ParameterConvention newCalleeConvention,
ValueKind kind) {
if (fnEI == newEI) return;
fnType = adjustFunctionType(fnType, newEI, newCalleeConvention);
SILType resTy = SILType::getPrimitiveObjectType(fnType);
SILValue converted;
if (kind == ValueKind::ConvertFunctionInst) {
converted = B.createConvertFunction(loc, fn.forward(*this), resTy);
} else {
assert(kind == ValueKind::ThinToThickFunctionInst);
converted = B.createThinToThickFunction(loc, fn.forward(*this), resTy);
}
fnEI = newEI;
fn = emitManagedRValueWithCleanup(converted);
};