-
Notifications
You must be signed in to change notification settings - Fork 10.4k
/
Copy pathSILGenDecl.cpp
2168 lines (1823 loc) · 78.5 KB
/
SILGenDecl.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
//===--- SILGenDecl.cpp - Implements Lowering of ASTs -> SIL for Decls ----===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
#include "SILGen.h"
#include "Initialization.h"
#include "RValue.h"
#include "Scope.h"
#include "SILGenDynamicCast.h"
#include "swift/SIL/FormalLinkage.h"
#include "swift/SIL/PrettyStackTrace.h"
#include "swift/SIL/SILArgument.h"
#include "swift/SIL/SILDebuggerClient.h"
#include "swift/SIL/SILType.h"
#include "swift/SIL/SILWitnessVisitor.h"
#include "swift/SIL/TypeLowering.h"
#include "swift/AST/AST.h"
#include "swift/AST/GenericEnvironment.h"
#include "swift/AST/Mangle.h"
#include "swift/AST/ASTMangler.h"
#include "swift/AST/Module.h"
#include "swift/AST/NameLookup.h"
#include "swift/AST/ProtocolConformance.h"
#include "llvm/ADT/SmallString.h"
#include <iterator>
using namespace swift;
using namespace Mangle;
using namespace Lowering;
void Initialization::_anchor() {}
void SILDebuggerClient::anchor() {}
namespace {
/// A "null" initialization that indicates that any value being initialized
/// into this initialization should be discarded. This represents AnyPatterns
/// (that is, 'var (_)') that bind to values without storing them.
class BlackHoleInitialization : public Initialization {
public:
BlackHoleInitialization() {}
SILValue getAddressOrNull() const override { return SILValue(); }
bool canSplitIntoTupleElements() const override {
return true;
}
MutableArrayRef<InitializationPtr>
splitIntoTupleElements(SILGenFunction &gen, SILLocation loc,
CanType type,
SmallVectorImpl<InitializationPtr> &buf) override {
// "Destructure" an ignored binding into multiple ignored bindings.
for (auto fieldType : cast<TupleType>(type)->getElementTypes()) {
(void) fieldType;
buf.push_back(InitializationPtr(new BlackHoleInitialization()));
}
return buf;
}
void copyOrInitValueInto(SILGenFunction &gen, SILLocation loc,
ManagedValue value, bool isInit) override {
/// This just ignores the provided value.
}
void finishUninitialized(SILGenFunction &gen) override {
// do nothing
}
};
} // end anonymous namespace
static void copyOrInitValueIntoHelper(
SILGenFunction &SGF, SILLocation loc, ManagedValue value, bool isInit,
ArrayRef<InitializationPtr> subInitializations,
llvm::function_ref<ManagedValue(ManagedValue, unsigned, SILType)> func) {
auto sourceType = value.getType().castTo<TupleType>();
auto sourceSILType = value.getType();
for (unsigned i = 0, e = sourceType->getNumElements(); i != e; ++i) {
SILType fieldTy = sourceSILType.getTupleElementType(i);
ManagedValue elt = func(value, i, fieldTy);
subInitializations[i]->copyOrInitValueInto(SGF, loc, elt, isInit);
subInitializations[i]->finishInitialization(SGF);
}
}
void TupleInitialization::copyOrInitValueInto(SILGenFunction &SGF,
SILLocation loc,
ManagedValue value, bool isInit) {
// In the object case, we perform a borrow + extract + copy sequence. This is
// because we do not have a destructure operation.
if (value.getType().isObject()) {
value = value.borrow(SGF, loc);
return copyOrInitValueIntoHelper(
SGF, loc, value, isInit, SubInitializations,
[&](ManagedValue aggregate, unsigned i,
SILType fieldType) -> ManagedValue {
auto elt = SGF.B.createTupleExtract(loc, aggregate, i, fieldType);
return SGF.B.createCopyValue(loc, elt);
});
}
// In the address case, we can support takes directly, so forward the cleanup
// of the aggregate and create takes of the underlying addresses.
value = ManagedValue::forUnmanaged(value.forward(SGF));
return copyOrInitValueIntoHelper(
SGF, loc, value, isInit, SubInitializations,
[&](ManagedValue aggregate, unsigned i,
SILType fieldType) -> ManagedValue {
ManagedValue elt =
SGF.B.createTupleElementAddr(loc, value, i, fieldType);
if (!fieldType.isAddressOnly(SGF.F.getModule())) {
return SGF.B.createLoadTake(loc, elt);
}
return SGF.emitManagedRValueWithCleanup(elt.getValue());
});
}
void TupleInitialization::finishUninitialized(SILGenFunction &gen) {
for (auto &subInit : SubInitializations) {
subInit->finishUninitialized(gen);
}
}
namespace {
class CleanupClosureConstant : public Cleanup {
SILValue closure;
public:
CleanupClosureConstant(SILValue closure) : closure(closure) {}
void emit(SILGenFunction &gen, CleanupLocation l) override {
gen.B.emitDestroyValueOperation(l, closure);
}
void dump(SILGenFunction &) const override {
#ifndef NDEBUG
llvm::errs() << "CleanupClosureConstant\n"
<< "State:" << getState() << "\n"
<< "closure:" << closure << "\n";
#endif
}
};
} // end anonymous namespace
SubstitutionList SILGenFunction::getForwardingSubstitutions() {
return F.getForwardingSubstitutions();
}
void SILGenFunction::visitFuncDecl(FuncDecl *fd) {
// Generate the local function body.
SGM.emitFunction(fd);
}
MutableArrayRef<InitializationPtr>
SingleBufferInitialization::
splitIntoTupleElements(SILGenFunction &gen, SILLocation loc, CanType type,
SmallVectorImpl<InitializationPtr> &buf) {
assert(SplitCleanups.empty() && "getting sub-initializations twice?");
return splitSingleBufferIntoTupleElements(gen, loc, type, getAddress(), buf,
SplitCleanups);
}
MutableArrayRef<InitializationPtr>
SingleBufferInitialization::
splitSingleBufferIntoTupleElements(SILGenFunction &gen, SILLocation loc,
CanType type, SILValue baseAddr,
SmallVectorImpl<InitializationPtr> &buf,
TinyPtrVector<CleanupHandle::AsPointer> &splitCleanups) {
// Destructure the buffer into per-element buffers.
for (auto i : indices(cast<TupleType>(type)->getElementTypes())) {
// Project the element.
SILValue eltAddr = gen.B.createTupleElementAddr(loc, baseAddr, i);
// Create an initialization to initialize the element.
auto &eltTL = gen.getTypeLowering(eltAddr->getType());
auto eltInit = gen.useBufferAsTemporary(eltAddr, eltTL);
// Remember the element cleanup.
auto eltCleanup = eltInit->getInitializedCleanup();
if (eltCleanup.isValid())
splitCleanups.push_back(eltCleanup);
buf.emplace_back(eltInit.release());
}
return buf;
}
void SingleBufferInitialization::
copyOrInitValueIntoSingleBuffer(SILGenFunction &gen, SILLocation loc,
ManagedValue value, bool isInit,
SILValue destAddr) {
if (!isInit) {
assert(value.getValue() != destAddr && "copying in place?!");
value.copyInto(gen, destAddr, loc);
return;
}
// If we didn't evaluate into the initialization buffer, do so now.
if (value.getValue() != destAddr) {
value.forwardInto(gen, loc, destAddr);
} else {
// If we did evaluate into the initialization buffer, disable the
// cleanup.
value.forwardCleanup(gen);
}
}
void SingleBufferInitialization::finishInitialization(SILGenFunction &gen) {
// Forward all of the split element cleanups, assuming we made any.
for (CleanupHandle eltCleanup : SplitCleanups)
gen.Cleanups.forwardCleanup(eltCleanup);
}
void KnownAddressInitialization::anchor() const {
}
void TemporaryInitialization::finishInitialization(SILGenFunction &gen) {
SingleBufferInitialization::finishInitialization(gen);
if (Cleanup.isValid())
gen.Cleanups.setCleanupState(Cleanup, CleanupState::Active);
}
namespace {
class EndBorrowCleanup : public Cleanup {
SILValue original;
SILValue borrowed;
public:
EndBorrowCleanup(SILValue original, SILValue borrowed)
: original(original), borrowed(borrowed) {}
void emit(SILGenFunction &gen, CleanupLocation l) override {
gen.B.createEndBorrow(l, borrowed, original);
}
void dump(SILGenFunction &) const override {
#ifndef NDEBUG
llvm::errs() << "EndBorrowCleanup "
<< "State:" << getState() << "\n"
<< "original:" << original << "\n"
<< "borrowed:" << borrowed << "\n";
#endif
}
};
} // end anonymous namespace
namespace {
class ReleaseValueCleanup : public Cleanup {
SILValue v;
public:
ReleaseValueCleanup(SILValue v) : v(v) {}
void emit(SILGenFunction &gen, CleanupLocation l) override {
if (v->getType().isAddress())
gen.B.createDestroyAddr(l, v);
else
gen.B.emitDestroyValueOperation(l, v);
}
void dump(SILGenFunction &) const override {
#ifndef NDEBUG
llvm::errs() << "ReleaseValueCleanup\n"
<< "State:" << getState() << "\n"
<< "Value:" << v << "\n";
#endif
}
};
} // end anonymous namespace
namespace {
/// Cleanup to destroy an initialized variable.
class DeallocStackCleanup : public Cleanup {
SILValue Addr;
public:
DeallocStackCleanup(SILValue addr) : Addr(addr) {}
void emit(SILGenFunction &gen, CleanupLocation l) override {
gen.B.createDeallocStack(l, Addr);
}
void dump(SILGenFunction &) const override {
#ifndef NDEBUG
llvm::errs() << "DeallocStackCleanup\n"
<< "State:" << getState() << "\n"
<< "Addr:" << Addr << "\n";
#endif
}
};
} // end anonymous namespace
namespace {
/// Cleanup to destroy an initialized 'var' variable.
class DestroyLocalVariable : public Cleanup {
VarDecl *Var;
public:
DestroyLocalVariable(VarDecl *var) : Var(var) {}
void emit(SILGenFunction &gen, CleanupLocation l) override {
gen.destroyLocalVariable(l, Var);
}
void dump(SILGenFunction &) const override {
#ifndef NDEBUG
llvm::errs() << "DestroyLocalVariable\n"
<< "State:" << getState() << "\n";
// TODO: Make sure we dump var.
llvm::errs() << "\n";
#endif
}
};
} // end anonymous namespace
namespace {
/// Cleanup to destroy an uninitialized local variable.
class DeallocateUninitializedLocalVariable : public Cleanup {
VarDecl *Var;
public:
DeallocateUninitializedLocalVariable(VarDecl *var) : Var(var) {}
void emit(SILGenFunction &gen, CleanupLocation l) override {
gen.deallocateUninitializedLocalVariable(l, Var);
}
void dump(SILGenFunction &) const override {
#ifndef NDEBUG
llvm::errs() << "DeallocateUninitializedLocalVariable\n"
<< "State:" << getState() << "\n";
// TODO: Make sure we dump var.
llvm::errs() << "\n";
#endif
}
};
} // end anonymous namespace
namespace {
/// An initialization of a local 'var'.
class LocalVariableInitialization : public SingleBufferInitialization {
/// The local variable decl being initialized.
VarDecl *decl;
SILGenFunction &SGF;
/// The cleanup we pushed to deallocate the local variable before it
/// gets initialized.
CleanupHandle DeallocCleanup;
/// The cleanup we pushed to destroy and deallocate the local variable.
CleanupHandle ReleaseCleanup;
bool DidFinish = false;
public:
/// Sets up an initialization for the allocated box. This pushes a
/// CleanupUninitializedBox cleanup that will be replaced when
/// initialization is completed.
LocalVariableInitialization(VarDecl *decl, bool NeedsMarkUninit,
unsigned ArgNo, SILGenFunction &SGF)
: decl(decl), SGF(SGF) {
assert(decl->getDeclContext()->isLocalContext() &&
"can't emit a local var for a non-local var decl");
assert(decl->hasStorage() && "can't emit storage for a computed variable");
assert(!SGF.VarLocs.count(decl) && "Already have an entry for this decl?");
auto boxType = SGF.SGM.Types
.getContextBoxTypeForCapture(decl,
SGF.getLoweredType(decl->getType()).getSwiftRValueType(),
SGF.F.getGenericEnvironment(),
/*mutable*/ true);
// The variable may have its lifetime extended by a closure, heap-allocate
// it using a box.
AllocBoxInst *allocBox =
SGF.B.createAllocBox(decl, boxType, {decl->isLet(), ArgNo});
SILValue addr = SGF.B.createProjectBox(decl, allocBox, 0);
// Mark the memory as uninitialized, so DI will track it for us.
if (NeedsMarkUninit)
addr = SGF.B.createMarkUninitializedVar(decl, addr);
/// Remember that this is the memory location that we're emitting the
/// decl to.
SGF.VarLocs[decl] = SILGenFunction::VarLoc::get(addr, allocBox);
// Push a cleanup to destroy the local variable. This has to be
// inactive until the variable is initialized.
SGF.Cleanups.pushCleanupInState<DestroyLocalVariable>(CleanupState::Dormant,
decl);
ReleaseCleanup = SGF.Cleanups.getTopCleanup();
// Push a cleanup to deallocate the local variable.
SGF.Cleanups.pushCleanup<DeallocateUninitializedLocalVariable>(decl);
DeallocCleanup = SGF.Cleanups.getTopCleanup();
}
~LocalVariableInitialization() override {
assert(DidFinish && "did not call VarInit::finishInitialization!");
}
SILValue getAddressOrNull() const override {
assert(SGF.VarLocs.count(decl) && "did not emit var?!");
return SGF.VarLocs[decl].value;
}
void finishUninitialized(SILGenFunction &gen) override {
LocalVariableInitialization::finishInitialization(gen);
}
void finishInitialization(SILGenFunction &SGF) override {
SingleBufferInitialization::finishInitialization(SGF);
assert(!DidFinish &&
"called LocalVariableInitialization::finishInitialization twice!");
SGF.Cleanups.setCleanupState(DeallocCleanup, CleanupState::Dead);
SGF.Cleanups.setCleanupState(ReleaseCleanup, CleanupState::Active);
DidFinish = true;
}
};
} // end anonymous namespace
namespace {
/// Initialize a writeback buffer that receives the value of a 'let'
/// declaration.
class LetValueInitialization : public Initialization {
/// The VarDecl for the let decl.
VarDecl *vd;
/// The address of the buffer used for the binding, if this is an address-only
/// let.
SILValue address;
/// The cleanup we pushed to destroy the local variable.
CleanupHandle DestroyCleanup;
/// Cleanups we introduced when splitting.
TinyPtrVector<CleanupHandle::AsPointer> SplitCleanups;
bool DidFinish = false;
public:
LetValueInitialization(VarDecl *vd, SILGenFunction &gen) : vd(vd)
{
auto &lowering = gen.getTypeLowering(vd->getType());
// Decide whether we need a temporary stack buffer to evaluate this 'let'.
// There are three cases we need to handle here: parameters, initialized (or
// bound) decls, and uninitialized ones.
bool needsTemporaryBuffer;
bool isUninitialized = false;
assert(!isa<ParamDecl>(vd)
&& "should not bind function params on this path");
if (vd->getParentPatternBinding() && !vd->getParentInitializer()) {
// This value is uninitialized (and unbound) if it has a pattern binding
// decl, with no initializer value.
assert(!vd->hasNonPatternBindingInit() && "Bound values aren't uninit!");
// If this is a let-value without an initializer, then we need a temporary
// buffer. DI will make sure it is only assigned to once.
needsTemporaryBuffer = true;
isUninitialized = true;
} else {
// If this is a let with an initializer or bound value, we only need a
// buffer if the type is address only.
needsTemporaryBuffer =
lowering.isAddressOnly() && gen.silConv.useLoweredAddresses();
}
if (needsTemporaryBuffer) {
address = gen.emitTemporaryAllocation(vd, lowering.getLoweredType());
if (isUninitialized)
address = gen.B.createMarkUninitializedVar(vd, address);
DestroyCleanup = gen.enterDormantTemporaryCleanup(address, lowering);
gen.VarLocs[vd] = SILGenFunction::VarLoc::get(address);
} else if (!lowering.isTrivial()) {
// Push a cleanup to destroy the let declaration. This has to be
// inactive until the variable is initialized: if control flow exits the
// before the value is bound, we don't want to destroy the value.
gen.Cleanups.pushCleanupInState<DestroyLocalVariable>(
CleanupState::Dormant, vd);
DestroyCleanup = gen.Cleanups.getTopCleanup();
} else {
DestroyCleanup = CleanupHandle::invalid();
}
}
~LetValueInitialization() override {
assert(DidFinish && "did not call LetValueInit::finishInitialization!");
}
bool hasAddress() const { return (bool)address; }
// SingleBufferInitializations always have an address.
SILValue getAddressForInPlaceInitialization() const override {
// Emit into the buffer that 'let's produce for address-only values if
// we have it.
if (hasAddress()) return address;
return SILValue();
}
/// Return true if we can get the addresses of elements with the
/// 'getSubInitializationsForTuple' method.
///
/// Let-value initializations cannot be broken into constituent pieces if a
/// scalar value needs to be bound. If there is an address in play, then we
/// can initialize the address elements of the tuple though.
bool canSplitIntoTupleElements() const override {
return hasAddress();
}
MutableArrayRef<InitializationPtr>
splitIntoTupleElements(SILGenFunction &gen, SILLocation loc, CanType type,
SmallVectorImpl<InitializationPtr> &buf) override {
assert(SplitCleanups.empty());
return SingleBufferInitialization
::splitSingleBufferIntoTupleElements(gen, loc, type, getAddress(), buf,
SplitCleanups);
}
SILValue getAddressOrNull() const override {
return address;
}
void bindValue(SILValue value, SILGenFunction &gen) {
assert(!gen.VarLocs.count(vd) && "Already emitted this vardecl?");
// If we're binding an address to this let value, then we can use it as an
// address later. This happens when binding an address only parameter to
// an argument, for example.
if (value->getType().isAddress())
address = value;
gen.VarLocs[vd] = SILGenFunction::VarLoc::get(value);
// Emit a debug_value[_addr] instruction to record the start of this value's
// lifetime.
SILLocation PrologueLoc(vd);
PrologueLoc.markAsPrologue();
if (address)
gen.B.createDebugValueAddr(PrologueLoc, value);
else
gen.B.createDebugValue(PrologueLoc, value);
}
void copyOrInitValueInto(SILGenFunction &gen, SILLocation loc,
ManagedValue value, bool isInit) override {
// If this let value has an address, we can handle it just like a single
// buffer value.
if (hasAddress())
return SingleBufferInitialization::
copyOrInitValueIntoSingleBuffer(gen, loc, value, isInit, getAddress());
// Otherwise, we bind the value.
if (isInit) {
// Disable the rvalue expression cleanup, since the let value
// initialization has a cleanup that lives for the entire scope of the
// let declaration.
bindValue(value.forward(gen), gen);
} else {
// Disable the expression cleanup of the copy, since the let value
// initialization has a cleanup that lives for the entire scope of the
// let declaration.
bindValue(value.copyUnmanaged(gen, loc).forward(gen), gen);
}
}
void finishUninitialized(SILGenFunction &gen) override {
LetValueInitialization::finishInitialization(gen);
}
void finishInitialization(SILGenFunction &gen) override {
assert(!DidFinish &&
"called LetValueInit::finishInitialization twice!");
assert(gen.VarLocs.count(vd) && "Didn't bind a value to this let!");
// Deactivate any cleanups we made when splitting the tuple.
for (auto cleanup : SplitCleanups)
gen.Cleanups.forwardCleanup(cleanup);
// Activate the destroy cleanup.
if (DestroyCleanup != CleanupHandle::invalid())
gen.Cleanups.setCleanupState(DestroyCleanup, CleanupState::Active);
DidFinish = true;
}
};
} // end anonymous namespace
namespace {
/// Initialize a variable of reference-storage type.
class ReferenceStorageInitialization : public Initialization {
InitializationPtr VarInit;
public:
ReferenceStorageInitialization(InitializationPtr &&subInit)
: VarInit(std::move(subInit)) {}
SILValue getAddressOrNull() const override { return SILValue(); }
void copyOrInitValueInto(SILGenFunction &gen, SILLocation loc,
ManagedValue value, bool isInit) override {
// If this is not an initialization, copy the value before we translateIt,
// translation expects a +1 value.
if (isInit)
value.forwardInto(gen, loc, VarInit->getAddress());
else
value.copyInto(gen, VarInit->getAddress(), loc);
}
void finishUninitialized(SILGenFunction &gen) override {
ReferenceStorageInitialization::finishInitialization(gen);
}
void finishInitialization(SILGenFunction &gen) override {
VarInit->finishInitialization(gen);
}
};
} // end anonymous namespace
namespace {
/// Abstract base class for refutable pattern initializations.
class RefutablePatternInitialization : public Initialization {
/// This is the label to jump to if the pattern fails to match.
JumpDest failureDest;
public:
RefutablePatternInitialization(JumpDest failureDest)
: failureDest(failureDest) {
assert(failureDest.isValid() &&
"Refutable patterns can only exist in failable conditions");
}
JumpDest getFailureDest() const { return failureDest; }
SILValue getAddressOrNull() const override { return SILValue(); }
void copyOrInitValueInto(SILGenFunction &gen, SILLocation loc,
ManagedValue value, bool isInit) override = 0;
void bindVariable(SILLocation loc, VarDecl *var, ManagedValue value,
CanType formalValueType, SILGenFunction &SGF) {
// Initialize the variable value.
InitializationPtr init = SGF.emitInitializationForVarDecl(var);
RValue(SGF, loc, formalValueType, value).forwardInto(SGF, loc, init.get());
}
};
} // end anonymous namespace
namespace {
class ExprPatternInitialization : public RefutablePatternInitialization {
ExprPattern *P;
public:
ExprPatternInitialization(ExprPattern *P, JumpDest patternFailDest)
: RefutablePatternInitialization(patternFailDest), P(P) {}
void copyOrInitValueInto(SILGenFunction &gen, SILLocation loc,
ManagedValue value, bool isInit) override;
};
} // end anonymous namespace
void ExprPatternInitialization::
copyOrInitValueInto(SILGenFunction &SGF, SILLocation loc,
ManagedValue value, bool isInit) {
assert(isInit && "Only initialization is supported for refutable patterns");
FullExpr scope(SGF.Cleanups, CleanupLocation(P));
bindVariable(P, P->getMatchVar(), value,
P->getType()->getCanonicalType(), SGF);
// Emit the match test.
SILValue testBool;
{
FullExpr scope(SGF.Cleanups, CleanupLocation(P->getMatchExpr()));
testBool = SGF.emitRValueAsSingleValue(P->getMatchExpr()).
getUnmanagedValue();
}
SILBasicBlock *contBB = SGF.B.splitBlockForFallthrough();
auto falseBB = SGF.Cleanups.emitBlockForCleanups(getFailureDest(), loc);
SGF.B.createCondBranch(loc, testBool, contBB, falseBB);
SGF.B.setInsertionPoint(contBB);
}
namespace {
class EnumElementPatternInitialization : public RefutablePatternInitialization {
EnumElementDecl *ElementDecl;
InitializationPtr subInitialization;
public:
EnumElementPatternInitialization(EnumElementDecl *ElementDecl,
InitializationPtr &&subInitialization,
JumpDest patternFailDest)
: RefutablePatternInitialization(patternFailDest), ElementDecl(ElementDecl),
subInitialization(std::move(subInitialization)) {}
void copyOrInitValueInto(SILGenFunction &SGF, SILLocation loc,
ManagedValue value, bool isInit) override {
assert(isInit && "Only initialization is supported for refutable patterns");
emitEnumMatch(value, ElementDecl, subInitialization.get(), getFailureDest(),
loc, SGF);
}
static void emitEnumMatch(ManagedValue value, EnumElementDecl *ElementDecl,
Initialization *subInit, JumpDest FailureDest,
SILLocation loc, SILGenFunction &SGF);
void finishInitialization(SILGenFunction &SGF) override {
if (subInitialization.get())
subInitialization->finishInitialization(SGF);
}
};
} // end anonymous namespace
static bool shouldDisableCleanupOnFailurePath(ManagedValue value,
EnumElementDecl *elementDecl,
SILGenFunction &SGF) {
// If the enum is trivial, then there is no cleanup to disable.
if (value.isPlusZeroRValueOrTrivial()) return false;
// Check all of the members of the enum. If any have a non-trivial payload,
// then we can't disable the cleanup.
for (auto elt : elementDecl->getParentEnum()->getAllElements()) {
// Ignore the element that will be handled.
if (elt == elementDecl) continue;
// Elements without payloads are trivial.
if (!elt->getArgumentInterfaceType()) continue;
auto eltTy = value.getType().getEnumElementType(elt, SGF.SGM.M);
if (!eltTy.isTrivial(SGF.SGM.M))
return false;
}
return true;
}
void EnumElementPatternInitialization::
emitEnumMatch(ManagedValue value, EnumElementDecl *ElementDecl,
Initialization *subInit, JumpDest failureDest,
SILLocation loc, SILGenFunction &SGF) {
SILBasicBlock *contBB = SGF.B.splitBlockForFallthrough();
auto destination = std::make_pair(ElementDecl, contBB);
// Get a destination that runs all of the cleanups needed when existing on the
// failure path. If the enum we're testing is non-trivial, there will be a
// cleanup in this stack that will release its value.
//
// However, if the tested case is the only non-trivial case in the enum, then
// the destruction on the failure path will be a no-op, so we can disable the
// cleanup on that path. This is an important micro-optimization for
// Optional, since the .None case doesn't need to be cleaned up.
bool ShouldDisableCleanupOnFailure =
shouldDisableCleanupOnFailurePath(value, ElementDecl, SGF);
if (ShouldDisableCleanupOnFailure)
SGF.Cleanups.setCleanupState(value.getCleanup(), CleanupState::Dormant);
auto defaultBB = SGF.Cleanups.emitBlockForCleanups(failureDest, loc);
// Restore it if we disabled it.
if (ShouldDisableCleanupOnFailure)
SGF.Cleanups.setCleanupState(value.getCleanup(), CleanupState::Active);
if (value.getType().isAddress())
SGF.B.createSwitchEnumAddr(loc, value.getValue(), defaultBB, destination);
else
SGF.B.createSwitchEnum(loc, value.getValue(), defaultBB, destination);
SGF.B.setInsertionPoint(contBB);
// If the enum case has no bound value, we're done.
if (!ElementDecl->getArgumentInterfaceType()) {
assert(subInit == nullptr &&
"Cannot have a subinit when there is no value to match against");
return;
}
// Otherwise, the bound value for the enum case is available.
SILType eltTy = value.getType().getEnumElementType(ElementDecl, SGF.SGM.M);
auto &eltTL = SGF.getTypeLowering(eltTy);
// If the case value is provided to us as a BB argument as long as the enum
// is not address-only.
SILValue eltValue;
if (!value.getType().isAddress())
eltValue = contBB->createPHIArgument(eltTy, ValueOwnershipKind::Owned);
if (subInit == nullptr) {
// If there is no subinitialization, then we are done matching. Don't
// bother projecting out the address-only element value only to ignore it.
return;
}
if (value.getType().isAddress()) {
// If the enum is address-only, take from the enum we have and load it if
// the element value is loadable.
assert((eltTL.isTrivial() || value.hasCleanup())
&& "must be able to consume value");
eltValue = SGF.B.createUncheckedTakeEnumDataAddr(loc, value.forward(SGF),
ElementDecl, eltTy);
// Load a loadable data value.
if (eltTL.isLoadable())
eltValue =
eltTL.emitLoad(SGF.B, loc, eltValue, LoadOwnershipQualifier::Take);
} else {
// Otherwise, we're consuming this as a +1 value.
value.forward(SGF);
}
// Now we have a +1 value.
auto eltMV = SGF.emitManagedRValueWithCleanup(eltValue, eltTL);
// If the payload is indirect, project it out of the box.
if (ElementDecl->isIndirect() || ElementDecl->getParentEnum()->isIndirect()) {
SILValue boxedValue = SGF.B.createProjectBox(loc, eltMV.getValue(), 0);
auto &boxedTL = SGF.getTypeLowering(boxedValue->getType());
// SEMANTIC ARC TODO: Revisit this when the verifier is enabled.
if (boxedTL.isLoadable())
boxedValue = boxedTL.emitLoad(SGF.B, loc, boxedValue,
LoadOwnershipQualifier::Take);
// We must treat the boxed value as +0 since it may be shared. Copy it if
// nontrivial.
// TODO: Should be able to hand it off at +0 in some cases.
eltMV = ManagedValue::forUnmanaged(boxedValue);
eltMV = eltMV.copyUnmanaged(SGF, loc);
}
// Reabstract to the substituted type, if needed.
CanType substEltTy =
value.getType().getSwiftRValueType()
->getTypeOfMember(SGF.SGM.M.getSwiftModule(),
ElementDecl,
ElementDecl->getArgumentInterfaceType())
->getCanonicalType();
AbstractionPattern origEltTy =
(ElementDecl == SGF.getASTContext().getOptionalSomeDecl()
? AbstractionPattern(substEltTy)
: SGF.SGM.M.Types.getAbstractionPattern(ElementDecl));
eltMV = SGF.emitOrigToSubstValue(loc, eltMV, origEltTy, substEltTy);
// Pass the +1 value down into the sub initialization.
subInit->copyOrInitValueInto(SGF, loc, eltMV, /*is an init*/true);
}
namespace {
class IsPatternInitialization : public RefutablePatternInitialization {
IsPattern *pattern;
InitializationPtr subInitialization;
public:
IsPatternInitialization(IsPattern *pattern,
InitializationPtr &&subInitialization,
JumpDest patternFailDest)
: RefutablePatternInitialization(patternFailDest), pattern(pattern),
subInitialization(std::move(subInitialization)) {}
void copyOrInitValueInto(SILGenFunction &SGF, SILLocation loc,
ManagedValue value, bool isInit) override;
void finishInitialization(SILGenFunction &SGF) override {
if (subInitialization.get())
subInitialization->finishInitialization(SGF);
}
};
} // end anonymous namespace
void IsPatternInitialization::
copyOrInitValueInto(SILGenFunction &SGF, SILLocation loc,
ManagedValue value, bool isInit) {
assert(isInit && "Only initialization is supported for refutable patterns");
// Try to perform the cast to the destination type, producing an optional that
// indicates whether we succeeded.
auto destType = OptionalType::get(pattern->getCastTypeLoc().getType());
value = emitConditionalCheckedCast(SGF, loc, value, pattern->getType(),
destType, pattern->getCastKind(),
SGFContext())
.getAsSingleValue(SGF, loc);
// Now that we have our result as an optional, we can use an enum projection
// to do all the work.
EnumElementPatternInitialization::
emitEnumMatch(value, SGF.getASTContext().getOptionalSomeDecl(),
subInitialization.get(), getFailureDest(), loc, SGF);
}
namespace {
class BoolPatternInitialization : public RefutablePatternInitialization {
BoolPattern *pattern;
public:
BoolPatternInitialization(BoolPattern *pattern,
JumpDest patternFailDest)
: RefutablePatternInitialization(patternFailDest), pattern(pattern) {}
void copyOrInitValueInto(SILGenFunction &SGF, SILLocation loc,
ManagedValue value, bool isInit) override;
};
} // end anonymous namespace
void BoolPatternInitialization::
copyOrInitValueInto(SILGenFunction &SGF, SILLocation loc,
ManagedValue value, bool isInit) {
assert(isInit && "Only initialization is supported for refutable patterns");
// Extract the i1 from the Bool struct.
StructDecl *BoolStruct = cast<StructDecl>(SGF.getASTContext().getBoolDecl());
auto Members = BoolStruct->lookupDirect(SGF.getASTContext().Id_value_);
assert(Members.size() == 1 &&
"Bool should have only one property with name '_value'");
auto Member = dyn_cast<VarDecl>(Members[0]);
assert(Member &&"Bool should have a property with name '_value' of type Int1");
auto *i1Val = SGF.B.createStructExtract(loc, value.forward(SGF), Member);
// Branch on the boolean based on whether we're testing for true or false.
SILBasicBlock *trueBB = SGF.B.splitBlockForFallthrough();
auto contBB = trueBB;
auto falseBB = SGF.Cleanups.emitBlockForCleanups(getFailureDest(), loc);
if (!pattern->getValue())
std::swap(trueBB, falseBB);
SGF.B.createCondBranch(loc, i1Val, trueBB, falseBB);
SGF.B.setInsertionPoint(contBB);
}
namespace {
/// InitializationForPattern - A visitor for traversing a pattern, generating
/// SIL code to allocate the declared variables, and generating an
/// Initialization representing the needed initializations.
///
/// It is important that any Initialization created for a pattern that might
/// not have an immediate initializer implement finishUninitialized. Note
/// that this only applies to irrefutable patterns.
struct InitializationForPattern
: public PatternVisitor<InitializationForPattern, InitializationPtr>
{
SILGenFunction &SGF;
/// This is the place that should be jumped to if the pattern fails to match.
/// This is invalid for irrefutable pattern initializations.
JumpDest patternFailDest;
InitializationForPattern(SILGenFunction &SGF, JumpDest patternFailDest)
: SGF(SGF), patternFailDest(patternFailDest) {}
// Paren, Typed, and Var patterns are noops, just look through them.
InitializationPtr visitParenPattern(ParenPattern *P) {
return visit(P->getSubPattern());
}
InitializationPtr visitTypedPattern(TypedPattern *P) {
return visit(P->getSubPattern());
}
InitializationPtr visitVarPattern(VarPattern *P) {
return visit(P->getSubPattern());
}
// AnyPatterns (i.e, _) don't require any storage. Any value bound here will
// just be dropped.
InitializationPtr visitAnyPattern(AnyPattern *P) {
return InitializationPtr(new BlackHoleInitialization());
}
// Bind to a named pattern by creating a memory location and initializing it
// with the initial value.
InitializationPtr visitNamedPattern(NamedPattern *P) {
if (!P->getDecl()->hasName()) {
// Unnamed parameters don't require any storage. Any value bound here will
// just be dropped.
return InitializationPtr(new BlackHoleInitialization());
}
return SGF.emitInitializationForVarDecl(P->getDecl());
}
// Bind a tuple pattern by aggregating the component variables into a
// TupleInitialization.
InitializationPtr visitTuplePattern(TuplePattern *P) {
TupleInitialization *init = new TupleInitialization();
for (auto &elt : P->getElements())
init->SubInitializations.push_back(visit(elt.getPattern()));
return InitializationPtr(init);
}
InitializationPtr visitEnumElementPattern(EnumElementPattern *P) {
InitializationPtr subInit;
if (auto *subP = P->getSubPattern())
subInit = visit(subP);
auto *res = new EnumElementPatternInitialization(P->getElementDecl(),
std::move(subInit),
patternFailDest);
return InitializationPtr(res);
}
InitializationPtr visitOptionalSomePattern(OptionalSomePattern *P) {
InitializationPtr subInit = visit(P->getSubPattern());