forked from swiftlang/swift
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSILFunctionType.cpp
2436 lines (2098 loc) · 92.9 KB
/
SILFunctionType.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
//===--- SILFunctionType.cpp - Giving SIL types to AST functions ----------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2016 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 defines the native Swift ownership transfer conventions
// and works in concert with the importer to give the correct
// conventions to imported functions and types.
//
//===----------------------------------------------------------------------===//
#define DEBUG_TYPE "libsil"
#include "swift/SIL/SILType.h"
#include "swift/SIL/SILModule.h"
#include "swift/AST/AnyFunctionRef.h"
#include "swift/AST/Decl.h"
#include "swift/AST/DiagnosticsSIL.h"
#include "swift/AST/ForeignErrorConvention.h"
#include "swift/Basic/Fallthrough.h"
#include "clang/Analysis/DomainSpecific/CocoaConventions.h"
#include "clang/AST/Attr.h"
#include "clang/AST/DeclObjC.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/ErrorHandling.h"
using namespace swift;
using namespace swift::Lowering;
SILType SILFunctionType::getSILResult() {
CanType type;
if (NumDirectResults == 0) {
type = getASTContext().TheEmptyTupleType;
} else if (NumDirectResults == 1) {
type = getDirectResults()[0].getType();
} else {
auto &cache = getMutableSILResultCache();
if (cache) {
type = cache;
} else {
SmallVector<TupleTypeElt, 4> elts;
for (auto result : getDirectResults())
elts.push_back(result.getType());
type = CanType(TupleType::get(elts, getASTContext()));
cache = type;
}
}
return SILType::getPrimitiveObjectType(type);
}
SILType SILFunctionType::getCSemanticResult() {
assert(getLanguage() == SILFunctionLanguage::C);
assert(getNumAllResults() <= 1);
if (NumDirectResults == 0) {
return SILType::getPrimitiveObjectType(getASTContext().TheEmptyTupleType);
} else if (NumDirectResults == 1) {
return SILType::getPrimitiveObjectType(getDirectResults()[0].getType());
} else {
return SILType::getPrimitiveAddressType(getIndirectResults()[0].getType());
}
}
CanType SILFunctionType::getSelfInstanceType() const {
auto selfTy = getSelfParameter().getType();
// If this is a static method, get the instance type.
if (auto metaTy = dyn_cast<AnyMetatypeType>(selfTy))
return metaTy.getInstanceType();
return selfTy;
}
ProtocolDecl *
SILFunctionType::getDefaultWitnessMethodProtocol(ModuleDecl &M) const {
assert(getRepresentation() == SILFunctionTypeRepresentation::WitnessMethod);
auto selfTy = getSelfInstanceType();
if (auto paramTy = dyn_cast<GenericTypeParamType>(selfTy)) {
assert(paramTy->getDepth() == 0 && paramTy->getIndex() == 0);
auto protos = GenericSig->getConformsTo(paramTy, M);
assert(protos.size() == 1);
return protos[0];
}
return nullptr;
}
static CanType getKnownType(Optional<CanType> &cacheSlot, ASTContext &C,
StringRef moduleName, StringRef typeName) {
if (!cacheSlot) {
cacheSlot = ([&] {
Module *mod = C.getLoadedModule(C.getIdentifier(moduleName));
if (!mod)
return CanType();
// Do a general qualified lookup instead of a direct lookupValue because
// some of the types we want are reexported through overlays and
// lookupValue would only give us types actually declared in the overlays
// themselves.
SmallVector<ValueDecl *, 2> decls;
mod->lookupQualified(ModuleType::get(mod), C.getIdentifier(typeName),
NL_QualifiedDefault | NL_KnownNonCascadingDependency,
/*resolver=*/nullptr, decls);
if (decls.size() != 1)
return CanType();
const TypeDecl *typeDecl = dyn_cast<TypeDecl>(decls.front());
if (!typeDecl)
return CanType();
assert(typeDecl->getDeclaredType() &&
"bridged type must be type-checked");
return typeDecl->getDeclaredType()->getCanonicalType();
})();
}
CanType t = *cacheSlot;
// It is possible that we won't find a bridging type (e.g. String) when we're
// parsing the stdlib itself.
if (t) {
DEBUG(llvm::dbgs() << "Bridging type " << moduleName << '.' << typeName
<< " mapped to ";
if (t)
t->print(llvm::dbgs());
else
llvm::dbgs() << "<null>";
llvm::dbgs() << '\n');
}
return t;
}
#define BRIDGING_KNOWN_TYPE(BridgedModule,BridgedType) \
CanType TypeConverter::get##BridgedType##Type() { \
return getKnownType(BridgedType##Ty, M.getASTContext(), \
#BridgedModule, #BridgedType); \
}
#include "swift/SIL/BridgedTypes.def"
/// Adjust a function type to have a slightly different type.
CanAnyFunctionType Lowering::adjustFunctionType(CanAnyFunctionType t,
AnyFunctionType::ExtInfo extInfo) {
if (t->getExtInfo() == extInfo)
return t;
return CanAnyFunctionType(t->withExtInfo(extInfo));
}
/// Adjust a function type to have a slightly different type.
CanSILFunctionType Lowering::adjustFunctionType(CanSILFunctionType type,
SILFunctionType::ExtInfo extInfo,
ParameterConvention callee) {
if (type->getExtInfo() == extInfo &&
type->getCalleeConvention() == callee)
return type;
return SILFunctionType::get(type->getGenericSignature(),
extInfo,
callee,
type->getParameters(),
type->getAllResults(),
type->getOptionalErrorResult(),
type->getASTContext());
}
namespace {
enum class ConventionsKind : uint8_t {
Default = 0,
DefaultBlock = 1,
ObjCMethod = 2,
CFunctionType = 3,
CFunction = 4,
SelectorFamily = 5,
Deallocator = 6,
Capture = 7,
};
class Conventions {
ConventionsKind kind;
protected:
virtual ~Conventions() = default;
public:
Conventions(ConventionsKind k) : kind(k) {}
ConventionsKind getKind() const { return kind; }
virtual ParameterConvention
getIndirectParameter(unsigned index,
const AbstractionPattern &type) const = 0;
virtual ParameterConvention
getDirectParameter(unsigned index,
const AbstractionPattern &type) const = 0;
virtual ParameterConvention getCallee() const = 0;
virtual ResultConvention getResult(const TypeLowering &resultTL) const = 0;
virtual ParameterConvention
getIndirectSelfParameter(const AbstractionPattern &type) const = 0;
virtual ParameterConvention
getDirectSelfParameter(const AbstractionPattern &type) const = 0;
};
/// A visitor for breaking down formal result types into a SILResultInfo
/// and possibly some number of indirect-out SILParameterInfos,
/// matching the abstraction patterns of the original type.
class DestructureResults {
SILModule &M;
const Conventions &Convs;
SmallVectorImpl<SILResultInfo> &Results;
public:
DestructureResults(SILModule &M, const Conventions &conventions,
SmallVectorImpl<SILResultInfo> &results)
: M(M), Convs(conventions), Results(results) {}
void destructure(AbstractionPattern origType, CanType substType) {
// Recurse into tuples.
if (origType.isTuple()) {
auto substTupleType = cast<TupleType>(substType);
for (auto eltIndex : indices(substTupleType.getElementTypes())) {
AbstractionPattern origEltType =
origType.getTupleElementType(eltIndex);
CanType substEltType = substTupleType.getElementType(eltIndex);
destructure(origEltType, substEltType);
}
return;
}
auto &substResultTL = M.Types.getTypeLowering(origType, substType);
// Determine the result convention.
ResultConvention convention;
if (isReturnedIndirectly(origType, substType, substResultTL)) {
convention = ResultConvention::Indirect;
} else {
convention = Convs.getResult(substResultTL);
// Reduce conventions for trivial types to an unowned convention.
if (substResultTL.isTrivial()) {
switch (convention) {
case ResultConvention::Indirect:
case ResultConvention::Unowned:
case ResultConvention::UnownedInnerPointer:
// Leave these as-is.
break;
case ResultConvention::Autoreleased:
case ResultConvention::Owned:
// These aren't distinguishable from unowned for trivial types.
convention = ResultConvention::Unowned;
break;
}
}
}
SILResultInfo result(substResultTL.getLoweredType().getSwiftRValueType(),
convention);
Results.push_back(result);
}
/// Query whether the original type is returned indirectly given complete
/// lowering information about its substitution.
bool isReturnedIndirectly(AbstractionPattern origType,
CanType substType, const TypeLowering &substTL) {
// If the substituted type is returned indirectly, so must the
// unsubstituted type.
if ((origType.isTypeParameter() &&
!origType.isConcreteType(*M.getSwiftModule()) &&
!origType.requiresClass(*M.getSwiftModule())) ||
substTL.isReturnedIndirectly()) {
return true;
// If the substitution didn't change the type, then a negative
// response to the above is determinative as well.
} else if (origType.getType() == substType &&
!origType.getType()->hasTypeParameter()) {
return false;
// Otherwise, query specifically for the original type.
} else {
// FIXME: Get expansion from SILDeclRef
return SILType::isReturnedIndirectly(origType.getType(), M,
origType.getGenericSignature(),
ResilienceExpansion::Minimal);
}
}
};
/// A visitor for turning formal input types into SILParameterInfos,
/// matching the abstraction patterns of the original type.
///
/// If the original abstraction pattern is fully opaque, we must
/// pass the function's inputs as if the original type were the most
/// general function signature (expressed entirely in type
/// variables) which can be substituted to equal the given
/// signature.
///
/// The goal of the most general type is to be (1) unambiguous to
/// compute from the substituted type and (2) the same for every
/// possible generalization of that type. For example, suppose we
/// have a Vector<(Int,Int)->Bool>. Obviously, we would prefer to
/// store optimal function pointers directly in this array; and if
/// all uses of it are ungeneralized, we'd get away with that. But
/// suppose the vector is passed to a function like this:
/// func satisfiesAll<T>(v : Vector<(T,T)->Bool>, x : T, y : T) -> Bool
/// That function will expect to be able to pull values out with the
/// proper abstraction. The only type we can possibly expect to agree
/// upon is the most general form.
///
/// The precise way this works is that Vector's subscript operation
/// (assuming that's how it's being accessed) has this signature:
/// <X> Vector<X> -> Int -> X
/// which 'satisfiesAll' is calling with this substitution:
/// X := (T, T) -> Bool
/// Since 'satisfiesAll' has a function type substituting for an
/// unrestricted archetype, it expects the value returned to have the
/// most general possible form 'A -> B', which it will need to
/// de-generalize (by thunking) if it needs to pass it around as
/// a '(T, T) -> Bool' value.
///
/// It is only this sort of direct substitution in types that forces
/// the most general possible type to be selected; declarations will
/// generally provide a target generalization level. For example,
/// in a Vector<IntPredicate>, where IntPredicate is a struct (not a
/// tuple) with one field of type (Int, Int) -> Bool, all the
/// function pointers will be stored ungeneralized. Of course, such
/// a vector couldn't be passed to 'satisfiesAll'.
///
/// For most types, the most general type is simply a fresh,
/// unrestricted type variable. But unmaterializable types are not
/// valid results of substitutions, so this does not apply. The
/// most general form of an unmaterializable type preserves the
/// basic structure of the unmaterializable components, replacing
/// any materializable components with fresh type variables.
///
/// That is, if we have a substituted function type:
/// (UnicodeScalar, (Int, Float), Double) -> Bool
/// then its most general form is
/// A -> B
///
/// because there is a valid substitution
/// A := (UnicodeScalar, (Int, Float), Double)
/// B := Bool
///
/// But if we have a substituted function type:
/// (UnicodeScalar, (Int, Float), inout Double) -> Bool
/// then its most general form is
/// (A, B, inout C) -> D
/// because the substitution
/// X := (UnicodeScalar, (Int, Float), inout Double)
/// is invalid substitution, ultimately because 'inout Double'
/// is not materializable.
class DestructureInputs {
SILModule &M;
const Conventions &Convs;
const Optional<ForeignErrorConvention> &ForeignError;
SmallVectorImpl<SILParameterInfo> &Inputs;
unsigned NextOrigParamIndex = 0;
public:
DestructureInputs(SILModule &M, const Conventions &conventions,
const Optional<ForeignErrorConvention> &foreignError,
SmallVectorImpl<SILParameterInfo> &inputs)
: M(M), Convs(conventions), ForeignError(foreignError), Inputs(inputs) {}
void destructure(AbstractionPattern origType, CanType substType,
AnyFunctionType::ExtInfo extInfo) {
visitTopLevelType(origType, substType, extInfo);
maybeAddForeignErrorParameter();
}
private:
bool isClangTypeMoreIndirectThanSubstType(const clang::Type *clangTy,
CanType substTy) {
// A const pointer argument might have been imported as
// UnsafePointer, COpaquePointer, or a CF foreign class.
// (An ObjC class type wouldn't be const-qualified.)
if (clangTy->isPointerType()
&& clangTy->getPointeeType().isConstQualified()) {
// Peek through optionals.
if (auto substObjTy = substTy.getAnyOptionalObjectType())
substTy = substObjTy;
// Void pointers aren't usefully indirectable.
if (clangTy->isVoidPointerType())
return false;
if (auto eltTy = substTy->getAnyPointerElementType())
return isClangTypeMoreIndirectThanSubstType(
clangTy->getPointeeType().getTypePtr(), CanType(eltTy));
if (substTy->getAnyNominal() ==
M.getASTContext().getOpaquePointerDecl())
// TODO: We could conceivably have an indirect opaque ** imported
// as COpaquePointer. That shouldn't ever happen today, though,
// since we only ever indirect the 'self' parameter of functions
// imported as methods.
return false;
if (clangTy->getPointeeType()->getAs<clang::RecordType>()) {
// CF type as foreign class
if (substTy->getClassOrBoundGenericClass()
&& substTy->getClassOrBoundGenericClass()->isForeign())
return false;
}
return true;
}
return false;
}
/// Query whether the original type is address-only given complete
/// lowering information about its substitution.
bool isPassedIndirectly(AbstractionPattern origType, CanType substType,
const TypeLowering &substTL) {
auto &mod = *M.getSwiftModule();
// If the C type of the argument is a const pointer, but the Swift type
// isn't, treat it as indirect.
if (origType.isClangType()
&& isClangTypeMoreIndirectThanSubstType(origType.getClangType(),
substType)) {
return true;
}
// If the substituted type is passed indirectly, so must the
// unsubstituted type.
if ((origType.isTypeParameter() &&
!origType.isConcreteType(mod) &&
!origType.requiresClass(mod)) ||
substTL.isPassedIndirectly()) {
return true;
// If the substitution didn't change the type, then a negative
// response to the above is determinative as well.
} else if (origType.getType() == substType &&
!origType.getType()->hasTypeParameter()) {
return false;
// Otherwise, query specifically for the original type.
} else {
// FIXME: Get expansion from SILDeclRef
return SILType::isPassedIndirectly(origType.getType(), M,
origType.getGenericSignature(),
ResilienceExpansion::Minimal);
}
}
void visitSelfType(AbstractionPattern origType, CanType substType,
SILFunctionTypeRepresentation rep) {
auto &substTL =
M.Types.getTypeLowering(origType, substType);
ParameterConvention convention;
if (origType.getAs<InOutType>()) {
convention = ParameterConvention::Indirect_Inout;
} else if (isPassedIndirectly(origType, substType, substTL)) {
if (rep == SILFunctionTypeRepresentation::WitnessMethod)
convention = ParameterConvention::Indirect_In_Guaranteed;
else
convention = Convs.getIndirectSelfParameter(origType);
assert(isIndirectParameter(convention));
} else if (substTL.isTrivial()) {
convention = ParameterConvention::Direct_Unowned;
} else {
convention = Convs.getDirectSelfParameter(origType);
assert(!isIndirectParameter(convention));
}
maybeAddForeignErrorParameter();
auto loweredType = substTL.getLoweredType().getSwiftRValueType();
Inputs.push_back(SILParameterInfo(loweredType, convention));
}
/// This is a special entry point that allows destructure inputs to handle
/// self correctly.
void visitTopLevelType(AbstractionPattern origType, CanType substType,
AnyFunctionType::ExtInfo extInfo) {
// If we don't have 'self', we don't need to do anything special.
if (!extInfo.hasSelfParam()) {
return visit(origType, substType);
}
// Okay, handle 'self'.
if (CanTupleType substTupleType = dyn_cast<TupleType>(substType)) {
unsigned numEltTypes = substTupleType.getElementTypes().size();
assert(numEltTypes > 0);
// Process all the non-self parameters.
unsigned numNonSelfParams = numEltTypes - 1;
for (unsigned i = 0; i != numNonSelfParams; ++i) {
visit(origType.getTupleElementType(i),
substTupleType.getElementType(i));
}
// Process the self parameter.
visitSelfType(origType.getTupleElementType(numNonSelfParams),
substTupleType.getElementType(numNonSelfParams),
extInfo.getSILRepresentation());
} else {
visitSelfType(origType, substType,
extInfo.getSILRepresentation());
}
}
void visit(AbstractionPattern origType, CanType substType) {
// Expand tuples. But if the abstraction pattern is opaque, and
// the tuple type is materializable -- if it doesn't contain an
// l-value type -- then it's a valid target for substitution and
// we should not expand it.
if (isa<TupleType>(substType) &&
(!origType.isTypeParameter() ||
!substType->isMaterializable())) {
auto substTuple = cast<TupleType>(substType);
assert(origType.isTypeParameter() ||
origType.getNumTupleElements() == substTuple->getNumElements());
for (auto i : indices(substTuple.getElementTypes())) {
visit(origType.getTupleElementType(i),
substTuple.getElementType(i));
}
return;
}
maybeAddForeignErrorParameter();
unsigned origParamIndex = NextOrigParamIndex++;
auto &substTL = M.Types.getTypeLowering(origType, substType);
ParameterConvention convention;
if (isa<InOutType>(substType)) {
assert(origType.isTypeParameter() || origType.getAs<InOutType>());
convention = ParameterConvention::Indirect_Inout;
} else if (isPassedIndirectly(origType, substType, substTL)) {
convention = Convs.getIndirectParameter(origParamIndex, origType);
assert(isIndirectParameter(convention));
} else if (substTL.isTrivial()) {
convention = ParameterConvention::Direct_Unowned;
} else {
convention = Convs.getDirectParameter(origParamIndex, origType);
assert(!isIndirectParameter(convention));
}
auto loweredType = substTL.getLoweredType().getSwiftRValueType();
Inputs.push_back(SILParameterInfo(loweredType, convention));
}
void maybeAddForeignErrorParameter() {
if (!ForeignError ||
NextOrigParamIndex != ForeignError->getErrorParameterIndex())
return;
// Assume the error parameter doesn't have interesting lowering.
Inputs.push_back(SILParameterInfo(ForeignError->getErrorParameterType(),
ParameterConvention::Direct_Unowned));
NextOrigParamIndex++;
}
};
}
/// Create the appropriate SIL function type for the given formal type
/// and conventions.
///
/// The lowering of function types is generally sensitive to the
/// declared abstraction pattern. We want to be able to take
/// advantage of declared type information in order to, say, pass
/// arguments separately and directly; but we also want to be able to
/// call functions from generic code without completely embarrassing
/// performance. Therefore, different abstraction patterns induce
/// different argument-passing conventions, and we must introduce
/// implicit reabstracting conversions where necessary to map one
/// convention to another.
///
/// However, we actually can't reabstract arbitrary thin function
/// values while still leaving them thin, at least without costly
/// page-mapping tricks. Therefore, the representation must remain
/// consistent across all abstraction patterns.
///
/// We could reabstract block functions in theory, but (1) we don't
/// really need to and (2) doing so would be problematic because
/// stuffing something in an Optional currently forces it to be
/// reabstracted to the most general type, which means that we'd
/// expect the wrong abstraction conventions on bridged block function
/// types.
///
/// Therefore, we only honor abstraction patterns on thick or
/// polymorphic functions.
///
/// FIXME: we shouldn't just drop the original abstraction pattern
/// when we can't reabstract. Instead, we should introduce
/// dynamic-indirect argument-passing conventions and map opaque
/// archetypes to that, then respect those conventions in IRGen by
/// using runtime call construction.
///
/// \param conventions - conventions as expressed for the original type
static CanSILFunctionType getSILFunctionType(SILModule &M,
AbstractionPattern origType,
CanAnyFunctionType substFnInterfaceType,
AnyFunctionType::ExtInfo extInfo,
const Conventions &conventions,
const Optional<ForeignErrorConvention> &foreignError,
Optional<SILDeclRef> constant) {
// Per above, only fully honor opaqueness in the abstraction pattern
// for thick or polymorphic functions. We don't need to worry about
// non-opaque patterns because the type-checker forbids non-thick
// function types from having generic parameters or results.
if (origType.isTypeParameter() &&
substFnInterfaceType->getExtInfo().getSILRepresentation()
!= SILFunctionType::Representation::Thick &&
isa<FunctionType>(substFnInterfaceType)) {
origType = AbstractionPattern(M.Types.getCurGenericContext(),
substFnInterfaceType);
}
// Find the generic parameters.
CanGenericSignature genericSig = nullptr;
if (auto genFnType = dyn_cast<GenericFunctionType>(substFnInterfaceType)) {
genericSig = genFnType.getGenericSignature();
}
// Lower the interface type in a generic context.
GenericContextScope scope(M.Types, genericSig);
// Map 'throws' to the appropriate error convention.
Optional<SILResultInfo> errorResult;
assert((!foreignError || substFnInterfaceType->getExtInfo().throws()) &&
"foreignError was set but function type does not throw?");
if (substFnInterfaceType->getExtInfo().throws() && !foreignError) {
assert(!origType.isForeign() &&
"using native Swift error convention for foreign type!");
SILType exnType = SILType::getExceptionType(M.getASTContext());
assert(exnType.isObject());
errorResult = SILResultInfo(exnType.getSwiftRValueType(),
ResultConvention::Owned);
}
// Lower the result type.
AbstractionPattern origResultType = origType.getFunctionResultType();
CanType substFormalResultType = substFnInterfaceType.getResult();
// If we have a foreign error convention, restore the original result type.
if (foreignError) {
switch (foreignError->getKind()) {
// These conventions replace the result type.
case ForeignErrorConvention::ZeroResult:
case ForeignErrorConvention::NonZeroResult:
assert(substFormalResultType->isVoid());
substFormalResultType = foreignError->getResultType();
origResultType = AbstractionPattern(genericSig, substFormalResultType);
break;
// These conventions wrap the result type in a level of optionality.
case ForeignErrorConvention::NilResult:
assert(!substFormalResultType->getAnyOptionalObjectType());
substFormalResultType =
OptionalType::get(substFormalResultType)->getCanonicalType();
origResultType =
AbstractionPattern::getOptional(origResultType, OTK_Optional);
break;
// These conventions don't require changes to the formal error type.
case ForeignErrorConvention::ZeroPreservedResult:
case ForeignErrorConvention::NonNilError:
break;
}
}
// Destructure the result tuple type.
SmallVector<SILResultInfo, 8> results;
{
DestructureResults destructurer(M, conventions, results);
destructurer.destructure(origResultType, substFormalResultType);
}
// Destructure the input tuple type.
SmallVector<SILParameterInfo, 8> inputs;
{
DestructureInputs destructurer(M, conventions, foreignError, inputs);
destructurer.destructure(origType.getFunctionInputType(),
substFnInterfaceType.getInput(),
extInfo);
}
// Lower the capture context parameters, if any.
// But note that default arg generators can't capture anything right now,
// and if we ever add that ability, it will be a different capture list
// from the function to which the argument is attached.
if (constant && !constant->isDefaultArgGenerator())
if (auto function = constant->getAnyFunctionRef()) {
auto &Types = M.Types;
auto loweredCaptures = Types.getLoweredLocalCaptures(*function);
for (auto capture : loweredCaptures.getCaptures()) {
auto *VD = capture.getDecl();
auto type = VD->getType()->getCanonicalType();
type = ArchetypeBuilder::mapTypeOutOfContext(
function->getAsDeclContext(), type)->getCanonicalType();
auto &loweredTL = Types.getTypeLowering(
AbstractionPattern(genericSig, type), type);
auto loweredTy = loweredTL.getLoweredType();
switch (Types.getDeclCaptureKind(capture)) {
case CaptureKind::None:
break;
case CaptureKind::Constant: {
// Constants are captured by value.
ParameterConvention convention;
if (loweredTL.isAddressOnly()) {
convention = M.getOptions().EnableGuaranteedClosureContexts
? ParameterConvention::Indirect_In_Guaranteed
: ParameterConvention::Indirect_In;
} else if (loweredTL.isTrivial()) {
convention = ParameterConvention::Direct_Unowned;
} else {
convention = M.getOptions().EnableGuaranteedClosureContexts
? ParameterConvention::Direct_Guaranteed
: ParameterConvention::Direct_Owned;
}
SILParameterInfo param(loweredTy.getSwiftRValueType(), convention);
inputs.push_back(param);
break;
}
case CaptureKind::Box: {
// Lvalues are captured as a box that owns the captured value.
SILType ty = loweredTy.getAddressType();
CanType boxTy = SILBoxType::get(ty.getSwiftRValueType());
auto convention = M.getOptions().EnableGuaranteedClosureContexts
? ParameterConvention::Direct_Guaranteed
: ParameterConvention::Direct_Owned;
auto param = SILParameterInfo(boxTy, convention);
inputs.push_back(param);
break;
}
case CaptureKind::StorageAddress: {
// Non-escaping lvalues are captured as the address of the value.
SILType ty = loweredTy.getAddressType();
auto param = SILParameterInfo(ty.getSwiftRValueType(),
ParameterConvention::Indirect_InoutAliasable);
inputs.push_back(param);
break;
}
}
}
}
auto calleeConvention = ParameterConvention::Direct_Unowned;
if (extInfo.hasContext())
calleeConvention = conventions.getCallee();
// Always strip the auto-closure and no-escape bit.
// TODO: The noescape bit could be of interest to SIL optimizations.
// We should bring it back when we have those optimizations.
auto silExtInfo = SILFunctionType::ExtInfo()
.withRepresentation(extInfo.getSILRepresentation())
.withIsNoReturn(extInfo.isNoReturn());
return SILFunctionType::get(genericSig,
silExtInfo, calleeConvention,
inputs, results, errorResult,
M.getASTContext());
}
//===----------------------------------------------------------------------===//
// Deallocator SILFunctionTypes
//===----------------------------------------------------------------------===//
namespace {
// The convention for general deallocators.
struct DeallocatorConventions : Conventions {
DeallocatorConventions() : Conventions(ConventionsKind::Deallocator) {}
ParameterConvention getIndirectParameter(unsigned index,
const AbstractionPattern &type) const override {
llvm_unreachable("Deallocators do not have indirect parameters");
}
ParameterConvention getDirectParameter(unsigned index,
const AbstractionPattern &type) const override {
llvm_unreachable("Deallocators do not have non-self direct parameters");
}
ParameterConvention getCallee() const override {
llvm_unreachable("Deallocators do not have callees");
}
ResultConvention getResult(const TypeLowering &tl) const override {
// TODO: Put an unreachable here?
return ResultConvention::Owned;
}
ParameterConvention
getDirectSelfParameter(const AbstractionPattern &type) const override {
// TODO: Investigate whether or not it is
return ParameterConvention::Direct_Owned;
}
ParameterConvention
getIndirectSelfParameter(const AbstractionPattern &type) const override {
llvm_unreachable("Deallocators do not have indirect self parameters");
}
static bool classof(const Conventions *C) {
return C->getKind() == ConventionsKind::Deallocator;
}
};
} // end anonymous namespace
//===----------------------------------------------------------------------===//
// Default Convention FunctionTypes
//===----------------------------------------------------------------------===//
namespace {
/// The default Swift conventions.
struct DefaultConventions : Conventions {
DefaultConventions()
: Conventions(ConventionsKind::Default) {}
ParameterConvention getIndirectParameter(unsigned index,
const AbstractionPattern &type) const override {
return ParameterConvention::Indirect_In;
}
ParameterConvention getDirectParameter(unsigned index,
const AbstractionPattern &type) const override {
return ParameterConvention::Direct_Owned;
}
ParameterConvention getCallee() const override {
return DefaultThickCalleeConvention;
}
ResultConvention getResult(const TypeLowering &tl) const override {
return ResultConvention::Owned;
}
ParameterConvention
getDirectSelfParameter(const AbstractionPattern &type) const override {
return ParameterConvention::Direct_Guaranteed;
}
ParameterConvention
getIndirectSelfParameter(const AbstractionPattern &type) const override {
return ParameterConvention::Indirect_In_Guaranteed;
}
static bool classof(const Conventions *C) {
return C->getKind() == ConventionsKind::Default;
}
};
/// The default conventions for Swift initializing constructors.
struct DefaultInitializerConventions : DefaultConventions {
using DefaultConventions::DefaultConventions;
/// Initializers must take 'self' at +1, since they will return it back
/// at +1, and may chain onto Objective-C initializers that replace the
/// instance.
ParameterConvention
getDirectSelfParameter(const AbstractionPattern &type) const override {
return ParameterConvention::Direct_Owned;
}
ParameterConvention
getIndirectSelfParameter(const AbstractionPattern &type) const override {
return ParameterConvention::Indirect_In;
}
};
/// The default conventions for ObjC blocks.
struct DefaultBlockConventions : Conventions {
DefaultBlockConventions() : Conventions(ConventionsKind::DefaultBlock) {}
ParameterConvention getIndirectParameter(unsigned index,
const AbstractionPattern &type) const override {
llvm_unreachable("indirect block parameters unsupported");
}
ParameterConvention getDirectParameter(unsigned index,
const AbstractionPattern &type) const override {
return ParameterConvention::Direct_Unowned;
}
ParameterConvention getCallee() const override {
return ParameterConvention::Direct_Unowned;
}
ResultConvention getResult(const TypeLowering &tl) const override {
return ResultConvention::Autoreleased;
}
ParameterConvention
getDirectSelfParameter(const AbstractionPattern &type) const override {
llvm_unreachable("objc blocks do not have a self parameter");
}
ParameterConvention
getIndirectSelfParameter(const AbstractionPattern &type) const override {
llvm_unreachable("objc blocks do not have a self parameter");
}
static bool classof(const Conventions *C) {
return C->getKind() == ConventionsKind::DefaultBlock;
}
};
}
static CanSILFunctionType getNativeSILFunctionType(SILModule &M,
AbstractionPattern origType,
CanAnyFunctionType substInterfaceType,
AnyFunctionType::ExtInfo extInfo,
Optional<SILDeclRef> constant,
SILDeclRef::Kind kind) {
switch (extInfo.getSILRepresentation()) {
case SILFunctionType::Representation::Block:
case SILFunctionType::Representation::CFunctionPointer:
// TODO: Ought to support captures in block funcs.
return getSILFunctionType(M, origType, substInterfaceType,
extInfo, DefaultBlockConventions(),
None, constant);
case SILFunctionType::Representation::Thin:
case SILFunctionType::Representation::ObjCMethod:
case SILFunctionType::Representation::Thick:
case SILFunctionType::Representation::Method:
case SILFunctionType::Representation::WitnessMethod: {
switch (kind) {
case SILDeclRef::Kind::Initializer:
return getSILFunctionType(M, origType, substInterfaceType,
extInfo, DefaultInitializerConventions(),
None, constant);
case SILDeclRef::Kind::Func:
case SILDeclRef::Kind::Allocator:
case SILDeclRef::Kind::Destroyer:
case SILDeclRef::Kind::GlobalAccessor:
case SILDeclRef::Kind::GlobalGetter:
case SILDeclRef::Kind::DefaultArgGenerator:
case SILDeclRef::Kind::IVarInitializer:
case SILDeclRef::Kind::IVarDestroyer:
case SILDeclRef::Kind::EnumElement:
return getSILFunctionType(M, origType, substInterfaceType,
extInfo, DefaultConventions(),
None, constant);
case SILDeclRef::Kind::Deallocator:
return getSILFunctionType(M, origType, substInterfaceType,
extInfo, DeallocatorConventions(), None,
constant);
}
}
}
}
CanSILFunctionType swift::getNativeSILFunctionType(SILModule &M,
AbstractionPattern origType,
CanAnyFunctionType substInterfaceType,
SILDeclRef::Kind kind) {
AnyFunctionType::ExtInfo extInfo;
// Preserve type information from the original type if possible.
if (auto origFnType = origType.getAs<AnyFunctionType>()) {
extInfo = origFnType->getExtInfo();
// Otherwise, preserve function type attributes from the substituted type.
} else {
extInfo = substInterfaceType->getExtInfo();
}
return ::getNativeSILFunctionType(M, origType, substInterfaceType,
extInfo, None, kind);
}
//===----------------------------------------------------------------------===//
// Foreign SILFunctionTypes
//===----------------------------------------------------------------------===//
static bool isCFTypedef(const TypeLowering &tl, clang::QualType type) {
// If we imported a C pointer type as a non-trivial type, it was
// a foreign class type.
return !tl.isTrivial() && type->isPointerType();
}
/// Given nothing but a formal C parameter type that's passed
/// indirectly, deduce the convention for it.
///
/// Generally, whether the parameter is +1 is handled before this.
static ParameterConvention getIndirectCParameterConvention(clang::QualType type) {
// Non-trivial C++ types would be Indirect_Inout (at least in Itanium).
// A trivial const * parameter in C should be considered @in.
return ParameterConvention::Indirect_In;
}
/// Given a C parameter declaration whose type is passed indirectly,
/// deduce the convention for it.
///