-
Notifications
You must be signed in to change notification settings - Fork 10.4k
/
Copy pathSILGenExpr.cpp
4371 lines (3680 loc) · 169 KB
/
SILGenExpr.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
//===--- SILGenExpr.cpp - Implements Lowering of ASTs -> SIL for Exprs ----===//
//
// 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
//
//===----------------------------------------------------------------------===//
#include "SILGen.h"
#include "Scope.h"
#include "swift/AST/AST.h"
#include "swift/AST/Decl.h"
#include "swift/AST/DiagnosticsCommon.h"
#include "swift/AST/Expr.h"
#include "swift/AST/Types.h"
#include "swift/AST/ASTWalker.h"
#include "swift/Basic/Fallthrough.h"
#include "swift/Basic/SourceManager.h"
#include "swift/Basic/type_traits.h"
#include "swift/SIL/SILArgument.h"
#include "swift/SIL/SILDebuggerClient.h"
#include "swift/SIL/SILUndef.h"
#include "swift/SIL/TypeLowering.h"
#include "Initialization.h"
#include "LValue.h"
#include "RValue.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/Support/ConvertUTF.h"
#include "llvm/Support/MemoryBuffer.h"
#include "llvm/Support/SaveAndRestore.h"
using namespace swift;
using namespace Lowering;
void SILDebuggerClient::anchor() {}
SILGenFunction::OpaqueValueRAII::~OpaqueValueRAII() {
// Destroy the value, unless it was both uniquely referenced and consumed.
auto entry = Self.OpaqueValues.find(OpaqueValue);
if (Destroy &&
(!OpaqueValue->isUniquelyReferenced() || !entry->second.second)) {
SILValue &value = entry->second.first;
auto &lowering = Self.getTypeLowering(value.getType().getSwiftRValueType());
if (lowering.isTrivial()) {
// Nothing to do.
} else if (lowering.isAddressOnly()) {
Self.B.emitDestroyAddr(OpaqueValue, value);
} else {
lowering.emitDestroyRValue(Self.B, OpaqueValue, value);
}
}
// Remove the opaque value.
Self.OpaqueValues.erase(entry);
}
ManagedValue SILGenFunction::emitManagedRetain(SILLocation loc,
SILValue v) {
auto &lowering = getTypeLowering(v.getType().getSwiftRValueType());
return emitManagedRetain(loc, v, lowering);
}
ManagedValue SILGenFunction::emitManagedRetain(SILLocation loc,
SILValue v,
const TypeLowering &lowering) {
assert(lowering.getLoweredType() == v.getType());
if (lowering.isTrivial())
return ManagedValue::forUnmanaged(v);
assert(!lowering.isAddressOnly() && "cannot retain an unloadable type");
lowering.emitRetainValue(B, loc, v);
return emitManagedRValueWithCleanup(v, lowering);
}
ManagedValue SILGenFunction::emitManagedRValueWithCleanup(SILValue v) {
auto &lowering = getTypeLowering(v.getType());
return emitManagedRValueWithCleanup(v, lowering);
}
ManagedValue SILGenFunction::emitManagedRValueWithCleanup(SILValue v,
const TypeLowering &lowering) {
assert(lowering.getLoweredType() == v.getType());
if (lowering.isTrivial())
return ManagedValue::forUnmanaged(v);
return ManagedValue(v, enterDestroyCleanup(v));
}
ManagedValue SILGenFunction::emitManagedBufferWithCleanup(SILValue v) {
auto &lowering = getTypeLowering(v.getType());
return emitManagedBufferWithCleanup(v, lowering);
}
ManagedValue SILGenFunction::emitManagedBufferWithCleanup(SILValue v,
const TypeLowering &lowering) {
assert(lowering.getLoweredType().getAddressType() == v.getType());
if (lowering.isTrivial())
return ManagedValue::forUnmanaged(v);
return ManagedValue(v, enterDestroyCleanup(v));
}
static void destroyRValue(SILGenFunction &SGF, CleanupLocation loc,
SILValue value, const TypeLowering &valueTL) {
if (valueTL.isTrivial()) return;
if (valueTL.isAddressOnly()) {
SGF.B.emitDestroyAddr(loc, value);
} else {
valueTL.emitDestroyRValue(SGF.B, loc, value);
}
}
void SILGenFunction::emitExprInto(Expr *E, Initialization *I) {
// Handle the special case of copying an lvalue.
if (auto load = dyn_cast<LoadExpr>(E)) {
auto lv = emitLValue(load->getSubExpr());
emitCopyLValueInto(E, lv, I);
return;
}
RValue result = emitRValue(E, SGFContext(I));
if (result)
std::move(result).forwardInto(*this, I, E);
}
namespace {
class RValueEmitter
: public Lowering::ExprVisitor<RValueEmitter, RValue, SGFContext>
{
SILGenFunction &SGF;
typedef Lowering::ExprVisitor<RValueEmitter,RValue,SGFContext> super;
public:
RValueEmitter(SILGenFunction &SGF) : SGF(SGF) {}
using super::visit;
RValue visit(Expr *E) {
assert(!E->getType()->is<LValueType>() &&
!E->getType()->is<InOutType>() &&
"RValueEmitter shouldn't be called on lvalues");
return visit(E, SGFContext());
}
// These always produce lvalues.
RValue visitInOutExpr(InOutExpr *E, SGFContext C) {
LValue lv = SGF.emitLValue(E->getSubExpr());
return RValue(SGF, E, SGF.emitAddressOfLValue(E->getSubExpr(), lv));
}
RValue visitInOutConversionExpr(InOutConversionExpr *E, SGFContext C);
RValue visitApplyExpr(ApplyExpr *E, SGFContext C);
RValue visitDiscardAssignmentExpr(DiscardAssignmentExpr *E, SGFContext C) {
llvm_unreachable("cannot appear in rvalue");
}
RValue visitDeclRefExpr(DeclRefExpr *E, SGFContext C);
RValue visitSuperRefExpr(SuperRefExpr *E, SGFContext C);
RValue visitOtherConstructorDeclRefExpr(OtherConstructorDeclRefExpr *E,
SGFContext C);
RValue visitIntegerLiteralExpr(IntegerLiteralExpr *E, SGFContext C);
RValue visitFloatLiteralExpr(FloatLiteralExpr *E, SGFContext C);
RValue visitCharacterLiteralExpr(CharacterLiteralExpr *E, SGFContext C);
RValue emitStringLiteral(Expr *E, StringRef Str, SGFContext C,
StringLiteralExpr::Encoding encoding);
RValue visitStringLiteralExpr(StringLiteralExpr *E, SGFContext C);
RValue visitLoadExpr(LoadExpr *E, SGFContext C);
RValue visitDerivedToBaseExpr(DerivedToBaseExpr *E, SGFContext C);
RValue visitMetatypeConversionExpr(MetatypeConversionExpr *E,
SGFContext C);
RValue visitArchetypeToSuperExpr(ArchetypeToSuperExpr *E, SGFContext C);
RValue visitFunctionConversionExpr(FunctionConversionExpr *E,
SGFContext C);
RValue visitCovariantFunctionConversionExpr(
CovariantFunctionConversionExpr *E,
SGFContext C);
RValue visitCovariantReturnConversionExpr(
CovariantReturnConversionExpr *E,
SGFContext C);
RValue visitErasureExpr(ErasureExpr *E, SGFContext C);
RValue visitConditionalCheckedCastExpr(ConditionalCheckedCastExpr *E,
SGFContext C);
RValue visitIsaExpr(IsaExpr *E, SGFContext C);
RValue visitCoerceExpr(CoerceExpr *E, SGFContext C);
RValue visitTupleExpr(TupleExpr *E, SGFContext C);
RValue visitScalarToTupleExpr(ScalarToTupleExpr *E, SGFContext C);
RValue visitMemberRefExpr(MemberRefExpr *E, SGFContext C);
RValue visitDynamicMemberRefExpr(DynamicMemberRefExpr *E, SGFContext C);
RValue visitDotSyntaxBaseIgnoredExpr(DotSyntaxBaseIgnoredExpr *E,
SGFContext C);
RValue visitModuleExpr(ModuleExpr *E, SGFContext C);
RValue visitTupleElementExpr(TupleElementExpr *E, SGFContext C);
RValue visitSubscriptExpr(SubscriptExpr *E, SGFContext C);
RValue visitDynamicSubscriptExpr(DynamicSubscriptExpr *E,
SGFContext C);
RValue visitTupleShuffleExpr(TupleShuffleExpr *E, SGFContext C);
RValue visitNewArrayExpr(NewArrayExpr *E, SGFContext C);
RValue visitMetatypeExpr(MetatypeExpr *E, SGFContext C);
RValue visitAbstractClosureExpr(AbstractClosureExpr *E, SGFContext C);
RValue visitInterpolatedStringLiteralExpr(InterpolatedStringLiteralExpr *E,
SGFContext C);
RValue visitMagicIdentifierLiteralExpr(MagicIdentifierLiteralExpr *E,
SGFContext C);
RValue visitCollectionExpr(CollectionExpr *E, SGFContext C);
RValue visitRebindSelfInConstructorExpr(RebindSelfInConstructorExpr *E,
SGFContext C);
RValue visitInjectIntoOptionalExpr(InjectIntoOptionalExpr *E, SGFContext C);
RValue visitBridgeToBlockExpr(BridgeToBlockExpr *E, SGFContext C);
RValue visitLValueConversionExpr(LValueConversionExpr *E, SGFContext C);
RValue visitLValueToPointerExpr(LValueToPointerExpr *E, SGFContext C);
RValue visitIfExpr(IfExpr *E, SGFContext C);
RValue visitDefaultValueExpr(DefaultValueExpr *E, SGFContext C);
RValue visitAssignExpr(AssignExpr *E, SGFContext C);
RValue visitBindOptionalExpr(BindOptionalExpr *E, SGFContext C);
RValue visitOptionalEvaluationExpr(OptionalEvaluationExpr *E,
SGFContext C);
RValue visitForceValueExpr(ForceValueExpr *E, SGFContext C);
RValue emitForceValue(SILLocation loc, Expr *E,
unsigned numOptionalEvaluations,
SGFContext C);
RValue visitOpenExistentialExpr(OpenExistentialExpr *E, SGFContext C);
RValue visitOpaqueValueExpr(OpaqueValueExpr *E, SGFContext C);
RValue emitUnconditionalCheckedCast(Expr *source,
SILLocation loc,
Type destType,
CheckedCastKind castKind,
SGFContext C);
};
}
RValue RValueEmitter::visitApplyExpr(ApplyExpr *E, SGFContext C) {
return SGF.emitApplyExpr(E, C);
}
SILValue SILGenFunction::emitEmptyTuple(SILLocation loc) {
return B.createTuple(loc,
getLoweredType(TupleType::getEmpty(SGM.M.getASTContext())), {});
}
SILValue SILGenFunction::emitGlobalFunctionRef(SILLocation loc,
SILDeclRef constant,
SILConstantInfo constantInfo) {
assert(constantInfo == getConstantInfo(constant));
assert(!LocalFunctions.count(constant) &&
"emitting ref to local constant without context?!");
if (constant.hasDecl() &&
isa<BuiltinUnit>(constant.getDecl()->getDeclContext())) {
return B.createBuiltinFunctionRef(loc, constant.getDecl()->getName(),
constantInfo.getSILType());
}
// If the constant is a curry thunk we haven't emitted yet, emit it.
if (constant.isCurried) {
if (!SGM.hasFunction(constant)) {
// Non-functions can't be referenced uncurried.
FuncDecl *fd = cast<FuncDecl>(constant.getDecl());
// Getters and setters can't be referenced uncurried.
assert(!fd->isGetterOrSetter());
// FIXME: Thunks for instance methods of generics.
assert(!(fd->isInstanceMember() && isa<ProtocolDecl>(fd->getDeclContext()))
&& "currying generic method not yet supported");
// FIXME: Curry thunks for generic methods don't work right yet, so skip
// emitting thunks for them
assert(!(fd->getType()->is<AnyFunctionType>() &&
fd->getType()->castTo<AnyFunctionType>()->getResult()
->is<PolymorphicFunctionType>()));
// Reference the next uncurrying level of the function.
SILDeclRef next = SILDeclRef(fd, SILDeclRef::Kind::Func,
SILDeclRef::ConstructAtBestResilienceExpansion,
constant.uncurryLevel + 1);
// If the function is fully uncurried and natively foreign, reference its
// foreign entry point.
if (!next.isCurried && fd->hasClangNode())
next = next.asForeign();
SGM.emitCurryThunk(constant, next, fd);
}
}
// Otherwise, if this is a foreign thunk we haven't emitted yet, emit it.
else if (constant.isForeignThunk()) {
if (!SGM.hasFunction(constant))
SGM.emitForeignThunk(constant);
}
return B.createFunctionRef(loc, SGM.getFunction(constant, NotForDefinition));
}
SILValue SILGenFunction::emitUnmanagedFunctionRef(SILLocation loc,
SILDeclRef constant) {
// If this is a reference to a local constant, grab it.
if (LocalFunctions.count(constant)) {
return LocalFunctions[constant];
}
// Otherwise, use a global FunctionRefInst.
return emitGlobalFunctionRef(loc, constant);
}
ManagedValue SILGenFunction::emitFunctionRef(SILLocation loc,
SILDeclRef constant) {
return emitFunctionRef(loc, constant, getConstantInfo(constant));
}
ManagedValue SILGenFunction::emitFunctionRef(SILLocation loc,
SILDeclRef constant,
SILConstantInfo constantInfo) {
// If this is a reference to a local constant, grab it.
if (LocalFunctions.count(constant)) {
SILValue v = LocalFunctions[constant];
return emitManagedRetain(loc, v);
}
// Otherwise, use a global FunctionRefInst.
SILValue c = emitGlobalFunctionRef(loc, constant, constantInfo);
return ManagedValue::forUnmanaged(c);
}
/// True if the global stored property requires lazy initialization.
static bool isGlobalLazilyInitialized(VarDecl *var) {
assert(!var->getDeclContext()->isLocalContext() &&
"not a global variable!");
assert(var->hasStorage() &&
"not a stored global variable!");
// Imports from C are never lazily initialized.
if (var->hasClangNode())
return false;
// Top-level global variables in the main source file and in the REPL are not
// lazily initialized.
auto sourceFileContext = dyn_cast<SourceFile>(var->getDeclContext());
if (!sourceFileContext)
return true;
return !sourceFileContext->isScriptMode();
}
static ManagedValue emitGlobalVariableRef(SILGenFunction &gen,
SILLocation loc, VarDecl *var) {
if (isGlobalLazilyInitialized(var)) {
// Call the global accessor to get the variable's address.
SILFunction *accessorFn = gen.SGM.getFunction(
SILDeclRef(var, SILDeclRef::Kind::GlobalAccessor),
NotForDefinition);
SILValue accessor = gen.B.createFunctionRef(loc, accessorFn);
auto accessorTy = accessor.getType().castTo<SILFunctionType>();
(void)accessorTy;
assert(!accessorTy->isPolymorphic()
&& "generic global variable accessors not yet implemented");
SILValue addr = gen.B.createApply(loc, accessor, accessor.getType(),
accessor.getType().castTo<SILFunctionType>()
->getInterfaceResult().getSILType(),
{}, {});
// FIXME: It'd be nice if the result of the accessor was natively an address.
addr = gen.B.createPointerToAddress(loc, addr,
gen.getLoweredType(var->getType()).getAddressType());
return ManagedValue::forLValue(addr);
}
// Global variables in main source files can be accessed directly.
// FIXME: And all global variables when lazy initialization is disabled.
SILValue addr = gen.B.createGlobalAddr(loc, var,
gen.getLoweredType(var->getType()).getAddressType());
return ManagedValue::forLValue(addr);
}
/// Emit the specified declaration as an LValue if possible, otherwise return
/// null.
ManagedValue SILGenFunction::emitLValueForDecl(SILLocation loc, VarDecl *var,
bool isDirectPropertyAccess) {
if (var->isDebuggerVar()) {
DebuggerClient *DebugClient = SGM.SwiftModule->getDebugClient();
assert(DebugClient && "Debugger variables with no debugger client");
SILDebuggerClient *SILDebugClient = DebugClient->getAsSILDebuggerClient();
assert(SILDebugClient && "Debugger client doesn't support SIL");
SILValue SV = SILDebugClient->emitLValueForVariable(var, B);
return ManagedValue::forLValue(SV);
}
// For local decls, use the address we allocated or the value if we have it.
auto It = VarLocs.find(var);
if (It != VarLocs.end()) {
// If this is a mutable lvalue, return it as an LValue.
if (It->second.isAddress())
return ManagedValue::forLValue(It->second.getAddress());
// If this is an address-only 'let', return its address as an lvalue.
if (It->second.getConstant().getType().isAddress())
return ManagedValue::forLValue(It->second.getConstant());
// Otherwise, it is an RValue let.
return ManagedValue();
}
// a getter produces an rvalue unless this is a direct access to storage.
if (!var->hasStorage() ||
(!isDirectPropertyAccess && var->hasAccessorFunctions()))
return ManagedValue();
// If this is a global variable, invoke its accessor function to get its
// address.
return emitGlobalVariableRef(*this, loc, var);
}
ManagedValue SILGenFunction::
emitRValueForDecl(SILLocation loc, ConcreteDeclRef declRef, Type ncRefType,
SGFContext C) {
assert(!ncRefType->is<LValueType>() &&
"RValueEmitter shouldn't be called on lvalues");
// Don't need to write back to decls loaded as rvalues.
DisableWritebackScope scope(*this);
// If this is an decl that we have an lvalue for, produce and return it.
ValueDecl *decl = declRef.getDecl();
if (!ncRefType) ncRefType = decl->getType();
CanType refType = ncRefType->getCanonicalType();
// If this is a reference to a type, produce a metatype.
if (isa<TypeDecl>(decl)) {
assert(!declRef.isSpecialized() &&
"Cannot handle specialized type references");
assert(decl->getType()->is<MetatypeType>() &&
"type declref does not have metatype type?!");
return ManagedValue::forUnmanaged(B.createMetatype(loc,
getLoweredType(refType)));
}
// If this is a reference to a var, produce an address or value.
if (auto *var = dyn_cast<VarDecl>(decl)) {
assert(!declRef.isSpecialized() &&
"Cannot handle specialized variable references");
// If this VarDecl is represented as an address, emit it as an lvalue, then
// perform a load to get the rvalue.
if (auto Result = emitLValueForDecl(loc, var))
return emitLoad(loc, Result.getLValueAddress(), getTypeLowering(refType),
C, IsNotTake);
// For local decls, use the address we allocated or the value if we have it.
auto It = VarLocs.find(decl);
if (It != VarLocs.end()) {
// Mutable lvalue and address-only 'let's are LValues.
assert(!It->second.isAddress() &&
!It->second.getConstant().getType().isAddress() &&
"LValue cases should be handled above");
auto Result = ManagedValue::forUnmanaged(It->second.getConstant());
// If the client can't handle a +0 result, retain it to get a +1.
return C.isPlusZeroOk() ? Result : Result.copyUnmanaged(*this, loc);
}
assert(var->hasAccessorFunctions() && "Unknown rvalue case");
// Global properties have no base or subscript.
return emitGetAccessor(loc, var,
ArrayRef<Substitution>(), RValueSource(),
/*isSuper=*/false, RValue(), C);
}
// If the referenced decl isn't a VarDecl, it should be a constant of some
// sort.
// If the referenced decl is a local func with context, then the SILDeclRef
// uncurry level is one deeper (for the context vars).
bool hasLocalCaptures = false;
unsigned uncurryLevel = 0;
if (auto *fd = dyn_cast<FuncDecl>(decl)) {
hasLocalCaptures = fd->getCaptureInfo().hasLocalCaptures();
if (hasLocalCaptures)
++uncurryLevel;
}
auto silDeclRef = SILDeclRef(decl, ResilienceExpansion::Minimal, uncurryLevel);
auto constantInfo = getConstantInfo(silDeclRef);
ManagedValue result = emitFunctionRef(loc, silDeclRef, constantInfo);
// Get the lowered AST types:
// - the original type
auto origLoweredFormalType = AbstractionPattern(constantInfo.LoweredType);
if (hasLocalCaptures) {
auto formalTypeWithoutCaptures =
cast<AnyFunctionType>(constantInfo.FormalType.getResult());
origLoweredFormalType =
AbstractionPattern(
SGM.Types.getLoweredASTFunctionType(formalTypeWithoutCaptures,0));
}
// - the substituted type
auto substFormalType = cast<AnyFunctionType>(refType);
auto substLoweredFormalType =
SGM.Types.getLoweredASTFunctionType(substFormalType, 0);
// If the declaration reference is specialized, create the partial
// application.
if (declRef.isSpecialized()) {
// Substitute the function type.
auto origFnType = result.getType().castTo<SILFunctionType>();
auto substFnType = origFnType->substInterfaceGenericArgs(
SGM.M, SGM.SwiftModule,
declRef.getSubstitutions());
auto closureType = getThickFunctionType(substFnType);
SILValue spec = B.createPartialApply(loc, result.forward(*this),
SILType::getPrimitiveObjectType(substFnType),
declRef.getSubstitutions(),
{ },
SILType::getPrimitiveObjectType(closureType));
result = emitManagedRValueWithCleanup(spec);
}
// Generalize if necessary.
return emitGeneralizedFunctionValue(loc, result, origLoweredFormalType,
substLoweredFormalType);
}
static AbstractionPattern getOrigFormalRValueType(Type formalStorageType) {
auto type = formalStorageType->getCanonicalType();
if (auto ref = dyn_cast<ReferenceStorageType>(type)) {
type = ref.getReferentType();
if (isa<WeakStorageType>(ref))
type = OptionalType::get(type)->getCanonicalType();
}
return AbstractionPattern(type);
}
/// Produce a singular RValue for a load from the specified property. This
/// is designed to work with RValue ManagedValue bases that are either +0 or +1.
ManagedValue SILGenFunction::
emitRValueForPropertyLoad(SILLocation loc, ManagedValue base,
bool isSuper,
VarDecl *FieldDecl,
ArrayRef<Substitution> substitutions,
bool isDirectPropertyAccess,
Type propTy, SGFContext C) {
// If this is a non-direct access to a computed property, call the getter.
if (FieldDecl->hasAccessorFunctions() && !isDirectPropertyAccess) {
// If the base is +0, and this is a non-protocol/archetype base, emit a
// retain_value to bring it to +1 since getters always take the base object
// at +1.
if (base.isPlusZeroRValueOrTrivial() &&
!base.getType().getSwiftRValueType()->isExistentialType() &&
!base.getType().getSwiftRValueType()->is<ArchetypeType>())
base = base.copyUnmanaged(*this, loc);
RValueSource baseRV = prepareAccessorBaseArg(loc, base,
FieldDecl->getGetter());
return emitGetAccessor(loc, FieldDecl, substitutions,
std::move(baseRV), isSuper, RValue(), C);
}
assert(FieldDecl->hasStorage() &&
"Cannot directly access value without storage");
// For static variables, emit a reference to the global variable backing
// them.
// FIXME: This has to be dynamically looked up for classes, and
// dynamically instantiated for generics.
if (FieldDecl->isStatic()) {
auto baseMeta = base.getType().castTo<MetatypeType>().getInstanceType();
(void)baseMeta;
assert(!baseMeta->is<BoundGenericType>() &&
"generic static stored properties not implemented");
assert((baseMeta->getStructOrBoundGenericStruct() ||
baseMeta->getEnumOrBoundGenericEnum()) &&
"static stored properties for classes/protocols not implemented");
return emitRValueForDecl(loc, FieldDecl, propTy, C);
}
// If the base is a reference type, just handle this as loading the lvalue.
if (base.getType().getSwiftRValueType()->hasReferenceSemantics()) {
// TODO: Enhance emitDirectIVarLValue to work with +0 bases directly.
if (base.isPlusZeroRValueOrTrivial())
base = base.copyUnmanaged(*this, loc);
LValue LV = emitDirectIVarLValue(loc, base, FieldDecl);
return emitLoadOfLValue(loc, LV, C);
}
// rvalue MemberRefExprs are produced in two cases: when accessing a 'let'
// decl member, and when the base is a (non-lvalue) struct.
assert(base.getType().getSwiftRValueType()->getAnyNominal() &&
"The base of an rvalue MemberRefExpr should be an rvalue value");
// If the accessed field is stored, emit a StructExtract on the base.
// Check for an abstraction difference.
bool hasAbstractionChange = false;
auto substFormalType = propTy->getCanonicalType();
AbstractionPattern origFormalType;
// FIXME: This crazy 'if' condition should not be required when we have
// reliable canonical type comparisons (i.e., interfacetypes get done). For
// now, not doing this causes us to emit extra pointless copies.
if (substFormalType->is<AnyFunctionType>() ||
substFormalType->is<TupleType>() ||
substFormalType->is<AnyMetatypeType>()) {
origFormalType = getOrigFormalRValueType(FieldDecl->getType());
hasAbstractionChange = origFormalType.getAsType() != substFormalType;
}
auto &lowering = getTypeLowering(propTy);
ManagedValue Result;
if (!base.getType().isAddress()) {
// For non-address-only structs, we emit a struct_extract sequence.
SILValue Scalar = B.createStructExtract(loc, base.getValue(), FieldDecl);
Result = ManagedValue::forUnmanaged(Scalar);
if (Result.getSwiftType()->is<ReferenceStorageType>()) {
// For @weak and @unowned types, convert the reference to the right
// pointer, producing a +1.
Scalar = emitConversionToSemanticRValue(loc, Scalar, lowering);
Result = emitManagedRValueWithCleanup(Scalar, lowering);
} else if (hasAbstractionChange || !C.isPlusZeroOk()) {
// If we have an abstraction change or if we have to produce a result at
// +1, then emit a RetainValue.
Result = Result.copyUnmanaged(*this, loc);
}
} else {
// For address-only sequences, the base is in memory. Emit a
// struct_element_addr to get to the field, and then load the element as an
// rvalue.
SILValue ElementPtr =
B.createStructElementAddr(loc, base.getValue(), FieldDecl);
Result = emitLoad(loc, ElementPtr, lowering,
hasAbstractionChange ? SGFContext() : C, IsNotTake);
}
// If we're accessing this member with an abstraction change, perform that
// now.
if (hasAbstractionChange)
Result = emitOrigToSubstValue(loc, Result, origFormalType,
substFormalType, C);
return Result;
}
RValue RValueEmitter::visitDeclRefExpr(DeclRefExpr *E, SGFContext C) {
auto Val = SGF.emitRValueForDecl(E, E->getDeclRef(), E->getType(), C);
return RValue(SGF, E, Val);
}
RValue RValueEmitter::visitSuperRefExpr(SuperRefExpr *E, SGFContext C) {
assert(!E->getType()->is<LValueType>() &&
"RValueEmitter shouldn't be called on lvalues");
auto Self = SGF.emitRValueForDecl(E, E->getSelf(), E->getSelf()->getType());
// Perform an upcast to convert self to the indicated super type.
auto Result = SGF.B.createUpcast(E, Self.getValue(),
SGF.getLoweredType(E->getType()));
return RValue(SGF, E, ManagedValue(Result, Self.getCleanup()));
}
RValue RValueEmitter::visitOtherConstructorDeclRefExpr(
OtherConstructorDeclRefExpr *E, SGFContext C) {
// This should always be a child of an ApplyExpr and so will be emitted by
// SILGenApply.
llvm_unreachable("unapplied reference to constructor?!");
}
RValue RValueEmitter::visitIntegerLiteralExpr(IntegerLiteralExpr *E,
SGFContext C) {
return RValue(SGF, E,
ManagedValue::forUnmanaged(SGF.B.createIntegerLiteral(E)));
}
RValue RValueEmitter::visitFloatLiteralExpr(FloatLiteralExpr *E,
SGFContext C) {
return RValue(SGF, E,
ManagedValue::forUnmanaged(SGF.B.createFloatLiteral(E)));
}
RValue RValueEmitter::visitCharacterLiteralExpr(CharacterLiteralExpr *E,
SGFContext C) {
return RValue(SGF, E,
ManagedValue::forUnmanaged(SGF.B.createIntegerLiteral(E)));
}
RValue RValueEmitter::emitStringLiteral(Expr *E, StringRef Str,
SGFContext C,
StringLiteralExpr::Encoding encoding) {
uint64_t Length;
bool isASCII = true;
for (unsigned char c : Str) {
if (c > 127) {
isASCII = false;
break;
}
}
StringLiteralInst::Encoding instEncoding;
switch (encoding) {
case StringLiteralExpr::UTF8:
instEncoding = StringLiteralInst::Encoding::UTF8;
Length = Str.size();
break;
case StringLiteralExpr::UTF16: {
instEncoding = StringLiteralInst::Encoding::UTF16;
// Transcode the string to UTF16 to get its length.
SmallVector<UTF16, 128> buffer(Str.size() + 1); // +1 for ending nulls.
const UTF8 *fromPtr = (const UTF8 *) Str.data();
UTF16 *toPtr = &buffer[0];
(void)ConvertUTF8toUTF16(&fromPtr, fromPtr + Str.size(),
&toPtr, toPtr + Str.size(), strictConversion);
// The length of the transcoded string in UTF-16 code points.
Length = toPtr - &buffer[0];
break;
}
}
// The string literal provides the data.
StringLiteralInst *string = SGF.B.createStringLiteral(E, Str, instEncoding);
CanType ty = E->getType()->getCanonicalType();
// The length is lowered as an integer_literal.
auto WordTy = SILType::getBuiltinWordType(SGF.getASTContext());
auto *lengthInst = SGF.B.createIntegerLiteral(E, WordTy, Length);
// The 'isascii' bit is lowered as an integer_literal.
auto Int1Ty = SILType::getBuiltinIntegerType(1, SGF.getASTContext());
auto *isASCIIInst = SGF.B.createIntegerLiteral(E, Int1Ty, isASCII);
ManagedValue EltsArray[] = {
ManagedValue::forUnmanaged(string),
ManagedValue::forUnmanaged(lengthInst),
ManagedValue::forUnmanaged(isASCIIInst)
};
ArrayRef<ManagedValue> Elts;
switch (instEncoding) {
case StringLiteralInst::Encoding::UTF16:
Elts = llvm::makeArrayRef(EltsArray).slice(0, 2);
break;
case StringLiteralInst::Encoding::UTF8:
Elts = EltsArray;
break;
}
return RValue(Elts, ty);
}
RValue RValueEmitter::visitStringLiteralExpr(StringLiteralExpr *E,
SGFContext C) {
return emitStringLiteral(E, E->getValue(), C, E->getEncoding());
}
RValue RValueEmitter::visitLoadExpr(LoadExpr *E, SGFContext C) {
LValue lv = SGF.emitLValue(E->getSubExpr());
return RValue(SGF, E, SGF.emitLoadOfLValue(E, lv, C));
}
SILValue SILGenFunction::emitTemporaryAllocation(SILLocation loc,
SILType ty) {
ty = ty.getObjectType();
auto alloc = B.createAllocStack(loc, ty);
enterDeallocStackCleanup(alloc->getContainerResult());
return alloc->getAddressResult();
}
SILValue SILGenFunction::
getBufferForExprResult(SILLocation loc, SILType ty, SGFContext C) {
// If you change this, change manageBufferForExprResult below as well.
// If we have a single-buffer "emit into" initialization, use that for the
// result.
if (Initialization *I = C.getEmitInto()) {
switch (I->kind) {
case Initialization::Kind::AddressBinding:
llvm_unreachable("can't emit into address binding");
case Initialization::Kind::LetValue:
// Emit into the buffer that 'let's produce for address-only values if
// we have it.
if (I->hasAddress())
return I->getAddress();
break;
case Initialization::Kind::Translating:
case Initialization::Kind::Ignored:
break;
case Initialization::Kind::Tuple:
// FIXME: For a single-element tuple, we could emit into the single field.
// The tuple initialization isn't contiguous, so we can't emit directly
// into it.
break;
case Initialization::Kind::SingleBuffer:
// Emit into the buffer.
return I->getAddress();
}
}
// If we couldn't emit into an Initialization, emit into a temporary
// allocation.
return emitTemporaryAllocation(loc, ty.getObjectType());
}
ManagedValue SILGenFunction::
manageBufferForExprResult(SILValue buffer, const TypeLowering &bufferTL,
SGFContext C) {
if (Initialization *I = C.getEmitInto()) {
switch (I->kind) {
case Initialization::Kind::AddressBinding:
llvm_unreachable("can't emit into address binding");
case Initialization::Kind::Ignored:
case Initialization::Kind::Translating:
case Initialization::Kind::Tuple:
break;
case Initialization::Kind::LetValue:
if (I->hasAddress()) {
I->finishInitialization(*this);
return ManagedValue::forInContext();
}
break;
case Initialization::Kind::SingleBuffer:
I->finishInitialization(*this);
return ManagedValue::forInContext();
}
}
// Add a cleanup for the temporary we allocated.
if (bufferTL.isTrivial())
return ManagedValue::forUnmanaged(buffer);
return ManagedValue(buffer, enterDestroyCleanup(buffer));
}
RValue RValueEmitter::visitDerivedToBaseExpr(DerivedToBaseExpr *E,
SGFContext C) {
ManagedValue original = SGF.emitRValueAsSingleValue(E->getSubExpr());
// Derived-to-base casts in the AST might not be reflected as such
// in the SIL type system, for example, a cast from DynamicSelf
// directly to its own Self type.
auto loweredResultTy = SGF.getLoweredType(E->getType());
if (original.getType() == loweredResultTy)
return RValue(SGF, E, original);
SILValue converted = SGF.B.createUpcast(E, original.getValue(),
loweredResultTy);
return RValue(SGF, E, ManagedValue(converted, original.getCleanup()));
}
RValue RValueEmitter::visitMetatypeConversionExpr(MetatypeConversionExpr *E,
SGFContext C) {
SILValue metaBase =
SGF.emitRValueAsSingleValue(E->getSubExpr()).getUnmanagedValue();
// Metatype conversion casts in the AST might not be reflected as
// such in the SIL type system, for example, a cast from DynamicSelf.Type
// directly to its own Self.Type.
auto loweredResultTy = SGF.getLoweredLoadableType(E->getType());
if (metaBase.getType() == loweredResultTy)
return RValue(SGF, E, ManagedValue::forUnmanaged(metaBase));
auto upcast = SGF.B.createUpcast(E, metaBase, loweredResultTy);
return RValue(SGF, E, ManagedValue::forUnmanaged(upcast));
}
RValue RValueEmitter::visitArchetypeToSuperExpr(ArchetypeToSuperExpr *E,
SGFContext C) {
ManagedValue archetype = SGF.emitRValueAsSingleValue(E->getSubExpr());
// Replace the cleanup with a new one on the superclass value so we always use
// concrete retain/release operations.
SILValue base = SGF.B.createUpcast(E,
archetype.forward(SGF),
SGF.getLoweredLoadableType(E->getType()));
return RValue(SGF, E, SGF.emitManagedRValueWithCleanup(base));
}
RValue RValueEmitter::visitFunctionConversionExpr(FunctionConversionExpr *e,
SGFContext C)
{
ManagedValue original = SGF.emitRValueAsSingleValue(e->getSubExpr());
// Retain the thinness of the original function type.
CanAnyFunctionType destTy =
cast<AnyFunctionType>(e->getType()->getCanonicalType());
if (original.getType().castTo<SILFunctionType>()->isThin())
destTy = getThinFunctionType(destTy);
SILType resultType = SGF.getLoweredType(destTy);
ManagedValue result;
if (resultType == original.getType()) {
// Don't make a conversion instruction if it's unnecessary.
result = original;
} else {
SILValue converted =
SGF.B.createConvertFunction(e, original.getValue(), resultType);
result = ManagedValue(converted, original.getCleanup());
}
return RValue(SGF, e, result);
}
RValue RValueEmitter::visitCovariantFunctionConversionExpr(
CovariantFunctionConversionExpr *e,
SGFContext C) {
ManagedValue original = SGF.emitRValueAsSingleValue(e->getSubExpr());
CanAnyFunctionType destTy
= cast<AnyFunctionType>(e->getType()->getCanonicalType());
SILType resultType = SGF.getLoweredType(destTy);
SILValue result = SGF.B.createConvertFunction(e,
original.forward(SGF),
resultType);
return RValue(SGF, e, SGF.emitManagedRValueWithCleanup(result));
}
static ManagedValue createUnsafeDowncast(SILGenFunction &gen,
SILLocation loc,
ManagedValue input,
SILType resultTy) {
SILType objectPtrTy = SILType::getObjectPointerType(gen.getASTContext());
SILValue result = gen.B.createRefToObjectPointer(loc,
input.forward(gen),
objectPtrTy);
result = gen.B.createObjectPointerToRef(loc, result, resultTy);
return gen.emitManagedRValueWithCleanup(result);
}
RValue RValueEmitter::visitCovariantReturnConversionExpr(
CovariantReturnConversionExpr *e,
SGFContext C) {
SILType resultType = SGF.getLoweredType(e->getType());
ManagedValue original = SGF.emitRValueAsSingleValue(e->getSubExpr());
ManagedValue result;
if (resultType.getSwiftRValueType().getAnyOptionalObjectType()) {
result = SGF.emitOptionalToOptional(e, original, resultType,
createUnsafeDowncast);
} else {
result = createUnsafeDowncast(SGF, e, original, resultType);
}
return RValue(SGF, e, result);
}
namespace {
/// An Initialization representing the concrete value buffer inside an
/// existential container.
class ExistentialValueInitialization : public SingleBufferInitialization {
SILValue valueAddr;
public:
ExistentialValueInitialization(SILValue valueAddr)
: valueAddr(valueAddr)
{}
SILValue getAddressOrNull() const override {
return valueAddr;
}
void finishInitialization(SILGenFunction &gen) {
// FIXME: Disable the DeinitExistential cleanup and enable the
// DestroyAddr cleanup for the existential container.
}
};
}
static RValue emitClassBoundErasure(SILGenFunction &gen, ErasureExpr *E) {
ManagedValue sub = gen.emitRValueAsSingleValue(E->getSubExpr());
SILType resultTy = gen.getLoweredLoadableType(E->getType());
SILValue v;
if (E->getSubExpr()->getType()->isExistentialType())
// If the source value is already of protocol type, we can use
// upcast_existential_ref to steal the already-initialized witness tables
// and concrete value.
v = gen.B.createUpcastExistentialRef(E, sub.getValue(), resultTy);
else