-
Notifications
You must be signed in to change notification settings - Fork 10.4k
/
Copy pathSILGenDecl.cpp
2615 lines (2251 loc) · 97.7 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 "Initialization.h"
#include "LValue.h"
#include "RValue.h"
#include "SILGen.h"
#include "SILGenDynamicCast.h"
#include "Scope.h"
#include "SwitchEnumBuilder.h"
#include "swift/AST/ASTMangler.h"
#include "swift/AST/DiagnosticsSIL.h"
#include "swift/AST/GenericEnvironment.h"
#include "swift/AST/Module.h"
#include "swift/AST/NameLookup.h"
#include "swift/AST/PropertyWrappers.h"
#include "swift/AST/ProtocolConformance.h"
#include "swift/Basic/Platform.h"
#include "swift/Basic/Assertions.h"
#include "swift/Basic/ProfileCounter.h"
#include "swift/SIL/FormalLinkage.h"
#include "swift/SIL/PrettyStackTrace.h"
#include "swift/SIL/SILArgument.h"
#include "swift/SIL/SILDebuggerClient.h"
#include "swift/SIL/SILInstruction.h"
#include "swift/SIL/SILSymbolVisitor.h"
#include "swift/SIL/SILType.h"
#include "swift/SIL/TypeLowering.h"
#include "llvm/ADT/SmallString.h"
#include <iterator>
using namespace swift;
using namespace Lowering;
// Utility for emitting diagnostics.
template <typename... T, typename... U>
static void diagnose(ASTContext &Context, SourceLoc loc, Diag<T...> diag,
U &&...args) {
Context.Diags.diagnose(loc, diag, std::forward<U>(args)...);
}
void Initialization::_anchor() {}
void SILDebuggerClient::anchor() {}
static void copyOrInitPackExpansionInto(SILGenFunction &SGF,
SILLocation loc,
SILValue tupleAddr,
CanPackType formalPackType,
unsigned componentIndex,
CleanupHandle componentCleanup,
Initialization *expansionInit,
bool isInit) {
auto expansionTy = tupleAddr->getType().getTupleElementType(componentIndex);
assert(expansionTy.is<PackExpansionType>());
auto opening = SGF.createOpenedElementValueEnvironment(expansionTy);
auto openedEnv = opening.first;
auto eltTy = opening.second;
assert(expansionInit);
assert(expansionInit->canPerformPackExpansionInitialization());
// Exit the component-wide cleanup for the expansion component.
if (componentCleanup.isValid())
SGF.Cleanups.forwardCleanup(componentCleanup);
SGF.emitDynamicPackLoop(loc, formalPackType, componentIndex, openedEnv,
[&](SILValue indexWithinComponent,
SILValue packExpansionIndex,
SILValue packIndex) {
expansionInit->performPackExpansionInitialization(SGF, loc,
indexWithinComponent,
[&](Initialization *eltInit) {
// Project the current tuple element.
auto eltAddr =
SGF.B.createTuplePackElementAddr(loc, packIndex, tupleAddr, eltTy);
SILValue elt = eltAddr;
if (!eltTy.isAddressOnly(SGF.F)) {
elt = SGF.B.emitLoadValueOperation(loc, elt,
LoadOwnershipQualifier::Take);
}
// Enter a cleanup for the current element, which we need to consume
// on this iteration of the loop, and the remaining elements in the
// expansion component, which we need to destroy if we throw from
// the initialization.
CleanupHandle eltCleanup = CleanupHandle::invalid();
CleanupHandle tailCleanup = CleanupHandle::invalid();
if (componentCleanup.isValid()) {
eltCleanup = SGF.enterDestroyCleanup(elt);
tailCleanup = SGF.enterPartialDestroyRemainingTupleCleanup(tupleAddr,
formalPackType, componentIndex, indexWithinComponent);
}
ManagedValue eltMV;
if (eltCleanup == CleanupHandle::invalid()) {
eltMV = ManagedValue::forRValueWithoutOwnership(elt);
} else {
eltMV = ManagedValue::forOwnedRValue(elt, eltCleanup);
}
// Perform the initialization. If this doesn't consume the
// element value, that's fine, we'll just destroy it as part of
// leaving the iteration.
eltInit->copyOrInitValueInto(SGF, loc, eltMV, isInit);
eltInit->finishInitialization(SGF);
// Deactivate the tail cleanup before continuing the loop.
if (tailCleanup.isValid())
SGF.Cleanups.forwardCleanup(tailCleanup);
});
});
expansionInit->finishInitialization(SGF);
}
void TupleInitialization::copyOrInitValueInto(SILGenFunction &SGF,
SILLocation loc,
ManagedValue value, bool isInit) {
auto sourceType = value.getType().castTo<TupleType>();
assert(sourceType->getNumElements() == SubInitializations.size());
// We have to emit a different pattern when there are pack expansions.
// Fortunately, we can assume this doesn't happen with objects because
// tuples contain pack expansions are address-only.
auto containsPackExpansion = sourceType.containsPackExpansionType();
CanPackType formalPackType;
if (containsPackExpansion)
formalPackType = FormalTupleType.getInducedPackType();
// Process all values before initialization all at once to ensure
// all cleanups are setup on all tuple elements before a potential
// early exit.
SmallVector<ManagedValue, 8> destructuredValues;
// In the object case, destructure the tuple.
if (value.getType().isObject()) {
assert(!containsPackExpansion);
SGF.B.emitDestructureValueOperation(loc, value, destructuredValues);
} else {
// In the address case, we forward the underlying value and store it
// into memory and then create a +1 cleanup. since we assume here
// that we have a +1 value since we are forwarding into memory.
assert(value.isPlusOneOrTrivial(SGF) &&
"Can not store a +0 value into memory?!");
CleanupCloner cloner(SGF, value);
SILValue v = value.forward(SGF);
auto sourceSILType = value.getType();
for (auto i : range(sourceType->getNumElements())) {
SILType fieldTy = sourceSILType.getTupleElementType(i);
if (containsPackExpansion && fieldTy.is<PackExpansionType>()) {
destructuredValues.push_back(
cloner.cloneForTuplePackExpansionComponent(v, formalPackType, i));
continue;
}
SILValue elt;
if (containsPackExpansion) {
auto packIndex = SGF.B.createScalarPackIndex(loc, i, formalPackType);
elt = SGF.B.createTuplePackElementAddr(loc, packIndex, v, fieldTy);
} else {
elt = SGF.B.createTupleElementAddr(loc, v, i, fieldTy);
}
if (!fieldTy.isAddressOnly(SGF.F)) {
elt = SGF.B.emitLoadValueOperation(loc, elt,
LoadOwnershipQualifier::Take);
}
destructuredValues.push_back(cloner.clone(elt));
}
}
assert(destructuredValues.size() == SubInitializations.size());
for (auto i : indices(destructuredValues)) {
if (containsPackExpansion) {
bool isPackExpansion =
(destructuredValues[i].getValue() == value.getValue());
assert(isPackExpansion ==
isa<PackExpansionType>(sourceType.getElementType(i)));
if (isPackExpansion) {
auto packAddr = destructuredValues[i].getValue();
auto componentCleanup = destructuredValues[i].getCleanup();
copyOrInitPackExpansionInto(SGF, loc, packAddr, formalPackType,
i, componentCleanup,
SubInitializations[i].get(), isInit);
continue;
}
}
SubInitializations[i]->copyOrInitValueInto(SGF, loc, destructuredValues[i],
isInit);
SubInitializations[i]->finishInitialization(SGF);
}
}
void TupleInitialization::finishUninitialized(SILGenFunction &SGF) {
for (auto &subInit : SubInitializations) {
subInit->finishUninitialized(SGF);
}
}
namespace {
class CleanupClosureConstant : public Cleanup {
SILValue closure;
public:
CleanupClosureConstant(SILValue closure) : closure(closure) {}
void emit(SILGenFunction &SGF, CleanupLocation l,
ForUnwind_t forUnwind) override {
SGF.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
SubstitutionMap SILGenFunction::getForwardingSubstitutionMap() {
return F.getForwardingSubstitutionMap();
}
void SILGenFunction::visitFuncDecl(FuncDecl *fd) {
// Generate the local function body.
SGM.emitFunction(fd);
}
MutableArrayRef<InitializationPtr>
SingleBufferInitialization::
splitIntoTupleElements(SILGenFunction &SGF, SILLocation loc, CanType type,
SmallVectorImpl<InitializationPtr> &buf) {
assert(SplitCleanups.empty() && "getting sub-initializations twice?");
auto address = getAddressForInPlaceInitialization(SGF, loc);
return splitSingleBufferIntoTupleElements(SGF, loc, type, address,
buf, SplitCleanups);
}
MutableArrayRef<InitializationPtr>
SingleBufferInitialization::
splitSingleBufferIntoTupleElements(SILGenFunction &SGF, SILLocation loc,
CanType type, SILValue baseAddr,
SmallVectorImpl<InitializationPtr> &buf,
TinyPtrVector<CleanupHandle::AsPointer> &splitCleanups) {
auto tupleType = cast<TupleType>(type);
// We can still split the initialization of a tuple with a pack
// expansion component (as long as the initializer is cooperative),
// but we have to emit a different code pattern.
bool hasExpansion = tupleType.containsPackExpansionType();
// If there's an expansion in the tuple, we'll need the induced pack
// type for the tuple elements below.
CanPackType inducedPackType;
if (hasExpansion) {
inducedPackType = tupleType.getInducedPackType();
}
// Destructure the buffer into per-element buffers.
for (auto i : indices(tupleType->getElementTypes())) {
// Project the element.
SILValue eltAddr;
// If this element is a pack expansion, we have to produce an
// Initialization that will drill appropriately to the right tuple
// element within a dynamic pack loop.
if (hasExpansion && isa<PackExpansionType>(tupleType.getElementType(i))) {
auto expansionInit =
TuplePackExpansionInitialization::create(SGF, baseAddr,
inducedPackType, i);
auto expansionCleanup = expansionInit->getExpansionCleanup();
if (expansionCleanup.isValid())
splitCleanups.push_back(expansionCleanup);
buf.emplace_back(expansionInit.release());
continue;
// If this element is scalar, but it's into a tuple with pack
// expansions, produce a structural pack index into the induced
// pack type and use that to project the right element.
} else if (hasExpansion) {
auto packIndex = SGF.B.createScalarPackIndex(loc, i, inducedPackType);
auto eltTy = baseAddr->getType().getTupleElementType(i);
eltAddr = SGF.B.createTuplePackElementAddr(loc, packIndex, baseAddr,
eltTy);
// Otherwise, we can just use simple projection.
} else {
eltAddr = SGF.B.createTupleElementAddr(loc, baseAddr, i);
}
// Create an initialization to initialize the element.
auto &eltTL = SGF.getTypeLowering(eltAddr->getType());
auto eltInit = SGF.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 &SGF, SILLocation loc,
ManagedValue value, bool isInit,
SILValue destAddr) {
// Emit an unchecked access around initialization of the local buffer to
// silence access marker verification.
//
// FIXME: This is not a good place for FormalEvaluationScope +
// UnenforcedFormalAccess. However, there's no way to identify the buffer
// initialization sequence after SILGen, and no easy way to wrap the
// Initialization in an access during top-level expression evaluation.
FormalEvaluationScope scope(SGF);
if (!isInit) {
assert(value.getValue() != destAddr && "copying in place?!");
SILValue accessAddr =
UnenforcedFormalAccess::enter(SGF, loc, destAddr, SILAccessKind::Modify);
value.copyInto(SGF, loc, accessAddr);
return;
}
// If we didn't evaluate into the initialization buffer, do so now.
if (value.getValue() != destAddr) {
SILValue accessAddr =
UnenforcedFormalAccess::enter(SGF, loc, destAddr, SILAccessKind::Modify);
value.forwardInto(SGF, loc, accessAddr);
} else {
// If we did evaluate into the initialization buffer, disable the
// cleanup.
value.forwardCleanup(SGF);
}
}
void SingleBufferInitialization::finishInitialization(SILGenFunction &SGF) {
// Forward all of the split element cleanups, assuming we made any.
for (CleanupHandle eltCleanup : SplitCleanups)
SGF.Cleanups.forwardCleanup(eltCleanup);
}
bool KnownAddressInitialization::isInPlaceInitializationOfGlobal() const {
return isa<GlobalAddrInst>(address);
}
bool TemporaryInitialization::isInPlaceInitializationOfGlobal() const {
return isa<GlobalAddrInst>(Addr);
}
void TemporaryInitialization::finishInitialization(SILGenFunction &SGF) {
SingleBufferInitialization::finishInitialization(SGF);
if (Cleanup.isValid())
SGF.Cleanups.setCleanupState(Cleanup, CleanupState::Active);
}
StoreBorrowInitialization::StoreBorrowInitialization(SILValue address)
: address(address) {
assert(isa<AllocStackInst>(address) ||
isa<MarkUnresolvedNonCopyableValueInst>(address) &&
"invalid destination for store_borrow initialization!?");
}
void StoreBorrowInitialization::copyOrInitValueInto(SILGenFunction &SGF,
SILLocation loc,
ManagedValue mv,
bool isInit) {
auto value = mv.getValue();
auto &lowering = SGF.getTypeLowering(value->getType());
if (lowering.isAddressOnly() && SGF.silConv.useLoweredAddresses()) {
llvm::report_fatal_error(
"Attempting to store_borrow an address-only value!?");
}
if (value->getType().isAddress()) {
value = SGF.emitManagedLoadBorrow(loc, value).getValue();
}
if (!isInit) {
value = lowering.emitCopyValue(SGF.B, loc, value);
}
storeBorrow = SGF.emitManagedStoreBorrow(loc, value, address);
}
SILValue StoreBorrowInitialization::getAddress() const {
if (storeBorrow) {
return storeBorrow.getValue();
}
return address;
}
ManagedValue StoreBorrowInitialization::getManagedAddress() const {
return storeBorrow;
}
namespace {
class ReleaseValueCleanup : public Cleanup {
SILValue v;
public:
ReleaseValueCleanup(SILValue v) : v(v) {}
void emit(SILGenFunction &SGF, CleanupLocation l,
ForUnwind_t forUnwind) override {
if (v->getType().isAddress())
SGF.B.createDestroyAddr(l, v);
else
SGF.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 deallocate a now-uninitialized variable.
class DeallocStackCleanup : public Cleanup {
SILValue Addr;
public:
DeallocStackCleanup(SILValue addr) : Addr(addr) {}
void emit(SILGenFunction &SGF, CleanupLocation l,
ForUnwind_t forUnwind) override {
SGF.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 &SGF, CleanupLocation l,
ForUnwind_t forUnwind) override {
SGF.destroyLocalVariable(l, Var);
}
void dump(SILGenFunction &SGF) const override {
#ifndef NDEBUG
llvm::errs() << "DestroyLocalVariable\n"
<< "State:" << getState() << "\n"
<< "Decl: ";
Var->print(llvm::errs());
llvm::errs() << "\n";
if (isActive()) {
auto &loc = SGF.VarLocs[Var];
assert((loc.box || loc.value) && "One of box or value should be set");
if (loc.box) {
llvm::errs() << "Box: " << loc.box << "\n";
} else {
llvm::errs() << "Value: " << loc.value << "\n";
}
}
llvm::errs() << "\n";
#endif
}
};
} // end anonymous namespace
namespace {
/// Cleanup to destroy an uninitialized local variable.
class DeallocateUninitializedLocalVariable : public Cleanup {
SILValue Box;
public:
DeallocateUninitializedLocalVariable(SILValue box) : Box(box) {}
void emit(SILGenFunction &SGF, CleanupLocation l,
ForUnwind_t forUnwind) override {
auto box = Box;
if (SGF.getASTContext().SILOpts.supportsLexicalLifetimes(SGF.getModule())) {
if (auto *bbi = dyn_cast<BeginBorrowInst>(box)) {
SGF.B.createEndBorrow(l, bbi);
box = bbi->getOperand();
}
}
SGF.B.createDeallocBox(l, box);
}
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;
/// The alloc_box instruction.
SILValue Box;
/// The projected address.
SILValue Addr;
/// 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,
std::optional<MarkUninitializedInst::Kind> kind,
uint16_t ArgNo, bool generateDebugInfo,
SILGenFunction &SGF)
: decl(decl) {
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?");
// The box type's context is lowered in the minimal resilience domain.
auto instanceType = SGF.SGM.Types.getLoweredRValueType(
TypeExpansionContext::minimal(), decl->getTypeInContext());
bool isNoImplicitCopy = instanceType->is<SILMoveOnlyWrappedType>();
// If our instance type is not already @moveOnly wrapped, and it's a
// no-implicit-copy parameter, wrap it.
if (!isNoImplicitCopy && !instanceType->isNoncopyable()) {
if (auto *pd = dyn_cast<ParamDecl>(decl)) {
isNoImplicitCopy = pd->isNoImplicitCopy();
isNoImplicitCopy |= pd->getSpecifier() == ParamSpecifier::Consuming;
if (pd->isSelfParameter()) {
auto *dc = pd->getDeclContext();
if (auto *fn = dyn_cast<FuncDecl>(dc)) {
auto accessKind = fn->getSelfAccessKind();
isNoImplicitCopy |= accessKind == SelfAccessKind::Consuming;
}
}
if (isNoImplicitCopy)
instanceType = SILMoveOnlyWrappedType::get(instanceType);
}
}
const bool isCopyable = isNoImplicitCopy || !instanceType->isNoncopyable();
auto boxType = SGF.SGM.Types.getContextBoxTypeForCapture(
decl, instanceType, SGF.F.getGenericEnvironment(),
/*mutable=*/ isCopyable || !decl->isLet());
// The variable may have its lifetime extended by a closure, heap-allocate
// it using a box.
std::optional<SILDebugVariable> DbgVar;
if (generateDebugInfo)
DbgVar = SILDebugVariable(decl->isLet(), ArgNo);
Box = SGF.B.createAllocBox(
decl, boxType, DbgVar, DoesNotHaveDynamicLifetime,
/*reflection*/ false, DoesNotUseMoveableValueDebugInfo,
!generateDebugInfo);
// Mark the memory as uninitialized, so DI will track it for us.
if (kind)
Box = SGF.B.createMarkUninitialized(decl, Box, kind.value());
// If we have a reference binding, mark it.
if (decl->getIntroducer() == VarDecl::Introducer::InOut)
Box = SGF.B.createMarkUnresolvedReferenceBindingInst(
decl, Box, MarkUnresolvedReferenceBindingInst::Kind::InOut);
if (SGF.getASTContext().SILOpts.supportsLexicalLifetimes(SGF.getModule())) {
auto loweredType = SGF.getTypeLowering(decl->getTypeInContext()).getLoweredType();
auto lifetime = SGF.F.getLifetime(decl, loweredType);
// The box itself isn't lexical--neither a weak reference nor an unsafe
// pointer to a box can be formed; and the box doesn't synchronize on
// deinit.
//
// Only add a lexical lifetime to the box if the variable it stores
// requires one.
Box =
SGF.B.createBeginBorrow(decl, Box, IsLexical_t(lifetime.isLexical()),
DoesNotHavePointerEscape, IsFromVarDecl);
}
Addr = SGF.B.createProjectBox(decl, Box, 0);
// 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. This references the
// box directly since it might be activated before we update
// SGF.VarLocs.
SGF.Cleanups.pushCleanup<DeallocateUninitializedLocalVariable>(Box);
DeallocCleanup = SGF.Cleanups.getTopCleanup();
}
~LocalVariableInitialization() override {
assert(DidFinish && "did not call VarInit::finishInitialization!");
}
SILValue getAddress() const {
assert(Addr);
return Addr;
}
/// If we have an address, returns the address. Otherwise, if we only have a
/// box, lazily projects it out and returns it.
SILValue getAddressForInPlaceInitialization(SILGenFunction &SGF,
SILLocation loc) override {
if (!Addr && Box) {
auto pbi = SGF.B.createProjectBox(loc, Box, 0);
return pbi;
}
return getAddress();
}
bool isInPlaceInitializationOfGlobal() const override {
return dyn_cast_or_null<GlobalAddrInst>(Addr);
}
void finishUninitialized(SILGenFunction &SGF) override {
LocalVariableInitialization::finishInitialization(SGF);
}
void finishInitialization(SILGenFunction &SGF) override {
/// Remember that this is the memory location that we've emitted the
/// decl to.
assert(SGF.VarLocs.count(decl) == 0 && "Already emitted the local?");
SGF.VarLocs[decl] = SILGenFunction::VarLoc(Addr,
SILAccessEnforcement::Dynamic, Box);
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 {
static void deallocateAddressable(SILGenFunction &SGF,
SILLocation l,
const SILGenFunction::VarLoc::AddressableBuffer::State &state) {
SGF.B.createEndBorrow(l, state.storeBorrow);
SGF.B.createDeallocStack(l, state.allocStack);
if (state.reabstraction) {
SGF.B.createDestroyValue(l, state.reabstraction);
}
}
/// Cleanup to deallocate the addressable buffer for a parameter or let
/// binding.
class DeallocateLocalVariableAddressableBuffer : public Cleanup {
ValueDecl *vd;
public:
DeallocateLocalVariableAddressableBuffer(ValueDecl *vd) : vd(vd) {}
void emit(SILGenFunction &SGF, CleanupLocation l,
ForUnwind_t forUnwind) override {
auto found = SGF.VarLocs.find(vd);
if (found == SGF.VarLocs.end()) {
return;
}
auto &loc = found->second;
if (auto &state = loc.addressableBuffer.state) {
// The addressable buffer was forced, so clean it up now.
deallocateAddressable(SGF, l, *state);
} else {
// Remember this insert location in case we need to force the addressable
// buffer later.
SILInstruction *marker = SGF.B.createTuple(l, {});
loc.addressableBuffer.cleanupPoints.emplace_back(marker);
}
}
void dump(SILGenFunction &SGF) const override {
#ifndef NDEBUG
llvm::errs() << "DeallocateLocalVariableAddressableBuffer\n"
<< "State:" << getState() << "\n"
<< "Decl: ";
vd->print(llvm::errs());
llvm::errs() << "\n";
#endif
}
};
/// 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 &SGF) : vd(vd) {
const TypeLowering *lowering = nullptr;
if (vd->isNoImplicitCopy()) {
lowering = &SGF.getTypeLowering(
SILMoveOnlyWrappedType::get(vd->getTypeInContext()->getCanonicalType()));
} else {
lowering = &SGF.getTypeLowering(vd->getTypeInContext());
}
// Decide whether we need a temporary stack buffer to evaluate this 'let'.
// There are four cases we need to handle here: parameters, initialized (or
// bound) decls, uninitialized ones, and async let declarations.
bool needsTemporaryBuffer;
bool isUninitialized = false;
assert(!isa<ParamDecl>(vd)
&& "should not bind function params on this path");
if (vd->getParentPatternBinding() &&
!vd->getParentExecutableInitializer()) {
// 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 (vd->isAsyncLet()) {
// If this is an async let, treat it like a let-value without an
// initializer. The initializer runs concurrently in a child task,
// and value will be initialized at the point the variable in the
// async let is used.
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 or is noncopyable.
//
// For noncopyable types, we always need to box them.
needsTemporaryBuffer =
(lowering->isAddressOnly() && SGF.silConv.useLoweredAddresses()) ||
lowering->getLoweredType().isMoveOnly(/*orWrapped=*/false);
}
// Make sure that we have a non-address only type when binding a
// @_noImplicitCopy let.
if (lowering->isAddressOnly() && vd->isNoImplicitCopy()) {
auto d = diag::noimplicitcopy_used_on_generic_or_existential;
diagnose(SGF.getASTContext(), vd->getLoc(), d);
}
if (needsTemporaryBuffer) {
bool lexicalLifetimesEnabled =
SGF.getASTContext().SILOpts.supportsLexicalLifetimes(SGF.getModule());
auto lifetime = SGF.F.getLifetime(vd, lowering->getLoweredType());
auto isLexical =
IsLexical_t(lexicalLifetimesEnabled && lifetime.isLexical());
address = SGF.emitTemporaryAllocation(vd, lowering->getLoweredType(),
DoesNotHaveDynamicLifetime,
isLexical, IsFromVarDecl);
if (isUninitialized)
address = SGF.B.createMarkUninitializedVar(vd, address);
DestroyCleanup = SGF.enterDormantTemporaryCleanup(address, *lowering);
SGF.VarLocs[vd] = SILGenFunction::VarLoc(address,
SILAccessEnforcement::Unknown);
}
// 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.
//
// Cleanups are required for all lexically scoped variables to delimite
// the variable scope, even if the cleanup does nothing.
SGF.Cleanups.pushCleanupInState<DestroyLocalVariable>(
CleanupState::Dormant, vd);
DestroyCleanup = SGF.Cleanups.getTopCleanup();
// If the binding has an addressable buffer forced, it should be cleaned
// up at this scope.
SGF.enterLocalVariableAddressableBufferScope(vd);
}
~LetValueInitialization() override {
assert(DidFinish && "did not call LetValueInit::finishInitialization!");
}
bool hasAddress() const { return (bool)address; }
bool canPerformInPlaceInitialization() const override {
return hasAddress();
}
bool isInPlaceInitializationOfGlobal() const override {
return isa<GlobalAddrInst>(address);
}
SILValue getAddressForInPlaceInitialization(SILGenFunction &SGF,
SILLocation loc) override {
// Emit into the buffer that 'let's produce for address-only values if
// we have it.
assert(hasAddress());
return address;
}
/// 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 &SGF, SILLocation loc, CanType type,
SmallVectorImpl<InitializationPtr> &buf) override {
assert(SplitCleanups.empty());
auto address = getAddressForInPlaceInitialization(SGF, loc);
return SingleBufferInitialization
::splitSingleBufferIntoTupleElements(SGF, loc, type, address, buf,
SplitCleanups);
}
/// This is a helper method for bindValue that creates a scopes operation for
/// the lexical variable lifetime and handles any changes to the value needed
/// for move-only values.
SILValue getValueForLexicalLifetimeBinding(SILGenFunction &SGF,
SILLocation PrologueLoc,
SILValue value, bool wasPlusOne) {
// TODO: emitPatternBindingInitialization creates fake local variables for
// metatypes within function_conversion expressions that operate on static
// functions. Creating SIL local variables for all these is impractical and
// undesirable. We need a better way of representing these "capture_list"
// locals in a way that doesn't produce SIL locals. For now, bypassing
// metatypes mostly avoids the issue, but it's not robust and doesn't allow
// SIL-level analysis of real metatype variables.
if (isa<MetatypeType>(value->getType().getASTType())) {
return value;
}
// Preprocess an owned moveonly value that had a cleanup. Even if we are
// only performing a borrow for our lexical lifetime, this ensures that
// defs see this initialization as consuming this value.
if (value->getOwnershipKind() == OwnershipKind::Owned &&
value->getType().isMoveOnlyWrapped()) {
assert(wasPlusOne);
// NOTE: If our type is trivial when not wrapped in a
// SILMoveOnlyWrappedType, this will return a trivial value. We rely
// on the checker to determine if this is an acceptable use of the
// value.
value =
SGF.B.createOwnedMoveOnlyWrapperToCopyableValue(PrologueLoc, value);
}
auto isLexical =
IsLexical_t(SGF.F.getLifetime(vd, value->getType()).isLexical());
switch (value->getOwnershipKind()) {
case OwnershipKind::None:
case OwnershipKind::Owned:
value = SGF.B.createMoveValue(PrologueLoc, value, isLexical,
DoesNotHavePointerEscape, IsFromVarDecl);
break;
case OwnershipKind::Guaranteed:
value = SGF.B.createBeginBorrow(PrologueLoc, value, isLexical,
DoesNotHavePointerEscape, IsFromVarDecl);
break;
case OwnershipKind::Unowned:
case OwnershipKind::Any:
llvm_unreachable("unexpected ownership");
}
if (vd->isNoImplicitCopy()) {
value =
SGF.B.createOwnedCopyableToMoveOnlyWrapperValue(PrologueLoc, value);
// fall-through to the owned move-only case...
}
if (value->getType().isMoveOnly(/*orWrapped=*/true)
&& value->getOwnershipKind() == OwnershipKind::Owned) {
value = SGF.B.createMarkUnresolvedNonCopyableValueInst(
PrologueLoc, value,
MarkUnresolvedNonCopyableValueInst::CheckKind::
ConsumableAndAssignable);
}
return value;
}
void bindValue(SILValue value, SILGenFunction &SGF, bool wasPlusOne,
SILLocation loc) {
assert(!SGF.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;
if (SGF.getASTContext().SILOpts.supportsLexicalLifetimes(SGF.getModule()))
value = getValueForLexicalLifetimeBinding(SGF, loc, value, wasPlusOne);
SGF.VarLocs[vd] = SILGenFunction::VarLoc(value,
SILAccessEnforcement::Unknown);
// Emit a debug_value[_addr] instruction to record the start of this value's
// lifetime, if permitted to do so.
if (!EmitDebugValueOnInit)
return;
// Use the scope from loc and diagnostic location from vd.
RegularLocation PrologueLoc(vd);
PrologueLoc.markAsPrologue();
SILDebugVariable DbgVar(vd->getName().str(), vd->isLet(), /*ArgNo=*/0);
SGF.B.emitDebugDescription(PrologueLoc, value, DbgVar);
}
void copyOrInitValueInto(SILGenFunction &SGF, 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(SGF, loc, value, isInit, address);
}
// 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.
bool isPlusOne = value.isPlusOne(SGF);
bindValue(value.forward(SGF), SGF, isPlusOne, loc);
} 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(SGF, loc).forward(SGF), SGF, true, loc);
}
}
void finishUninitialized(SILGenFunction &SGF) override {
LetValueInitialization::finishInitialization(SGF);
}
void finishInitialization(SILGenFunction &SGF) override {
assert(!DidFinish &&
"called LetValueInit::finishInitialization twice!");
assert(SGF.VarLocs.count(vd) && "Didn't bind a value to this let!");
// Deactivate any cleanups we made when splitting the tuple.
for (auto cleanup : SplitCleanups)
SGF.Cleanups.forwardCleanup(cleanup);
// Activate the destroy cleanup.
if (DestroyCleanup != CleanupHandle::invalid()) {
SGF.Cleanups.setCleanupState(DestroyCleanup, CleanupState::Active);
}
DidFinish = true;
}
};
} // end anonymous namespace