-
Notifications
You must be signed in to change notification settings - Fork 10.4k
/
Copy pathSILGenDecl.cpp
2332 lines (1996 loc) · 86.4 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 - 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 "Initialization.h"
#include "RValue.h"
#include "Scope.h"
#include "swift/SIL/SILArgument.h"
#include "swift/SIL/SILType.h"
#include "swift/SIL/TypeLowering.h"
#include "swift/AST/AST.h"
#include "swift/AST/Mangle.h"
#include "swift/AST/Module.h"
#include "swift/AST/NameLookup.h"
#include "swift/Basic/Fallthrough.h"
#include "swift/ClangImporter/ClangModule.h"
#include <iterator>
using namespace swift;
using namespace Mangle;
using namespace Lowering;
void Initialization::_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()
: Initialization(Initialization::Kind::Ignored)
{}
SILValue getAddressOrNull() const override { return SILValue(); }
ArrayRef<InitializationPtr> getSubInitializations() const override {
return {};
}
};
/// An Initialization subclass used to destructure tuple initializations.
class TupleElementInitialization : public SingleBufferInitialization {
public:
SILValue ElementAddr;
TupleElementInitialization(SILValue addr)
: ElementAddr(addr)
{}
SILValue getAddressOrNull() const override { return ElementAddr; }
void finishInitialization(SILGenFunction &gen) override {}
};
}
bool Initialization::canForwardInBranch() const {
switch (kind) {
case Kind::Ignored:
case Kind::SingleBuffer:
return true;
// These initializations expect to be activated exactly once.
case Kind::AddressBinding:
case Kind::LetValue:
case Kind::Translating:
return false;
case Kind::Tuple:
for (auto &subinit : getSubInitializations()) {
if (!subinit->canForwardInBranch())
return false;
}
return true;
}
llvm_unreachable("bad initialization kind!");
}
ArrayRef<InitializationPtr>
Initialization::getSubInitializationsForTuple(SILGenFunction &gen, CanType type,
SmallVectorImpl<InitializationPtr> &buf,
SILLocation Loc) {
assert(canSplitIntoSubelementAddresses() && "Client shouldn't call this");
switch (kind) {
case Kind::Tuple:
return getSubInitializations();
case Kind::Ignored:
// "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;
case Kind::LetValue:
case Kind::SingleBuffer: {
// Destructure the buffer into per-element buffers.
auto tupleTy = cast<TupleType>(type);
SILValue baseAddr = getAddress();
for (unsigned i = 0, size = tupleTy->getNumElements(); i < size; ++i) {
auto fieldType = tupleTy.getElementType(i);
SILType fieldTy = gen.getLoweredType(fieldType).getAddressType();
SILValue fieldAddr = gen.B.createTupleElementAddr(Loc,
baseAddr, i,
fieldTy);
buf.push_back(InitializationPtr(new
TupleElementInitialization(fieldAddr)));
}
finishInitialization(gen);
return buf;
}
case Kind::Translating:
// This could actually be done by collecting translated values, if
// we introduce new needs for translating initializations.
llvm_unreachable("cannot destructure a translating initialization");
case Kind::AddressBinding:
llvm_unreachable("cannot destructure an address binding initialization");
}
llvm_unreachable("bad initialization kind");
}
namespace {
class CleanupClosureConstant : public Cleanup {
SILValue closure;
public:
CleanupClosureConstant(SILValue closure) : closure(closure) {}
void emit(SILGenFunction &gen, CleanupLocation l) override {
gen.B.emitStrongRelease(l, closure);
}
};
}
ArrayRef<Substitution> SILGenFunction::getForwardingSubstitutions() {
if (auto gp = F.getContextGenericParams())
return buildForwardingSubstitutions(gp);
return {};
}
void SILGenFunction::visitFuncDecl(FuncDecl *fd) {
// Generate the local function body.
SGM.emitFunction(fd);
// If there are captures or we are in a generic context, build the local
// closure value for the function and store it as a local constant.
if (fd->getCaptureInfo().hasLocalCaptures()
|| F.getContextGenericParams()) {
SILValue closure = emitClosureValue(fd, SILDeclRef(fd),
getForwardingSubstitutions(), fd)
.forward(*this);
Cleanups.pushCleanup<CleanupClosureConstant>(closure);
LocalFunctions[SILDeclRef(fd)] = closure;
}
}
ArrayRef<InitializationPtr>
SingleBufferInitialization::getSubInitializations() const {
return {};
}
void TemporaryInitialization::finishInitialization(SILGenFunction &gen) {
if (Cleanup.isValid())
gen.Cleanups.setCleanupState(Cleanup, CleanupState::Active);
};
namespace {
/// An Initialization of a tuple pattern, such as "var (a,b)".
class TupleInitialization : public Initialization {
public:
/// The sub-Initializations aggregated by this tuple initialization.
/// The TupleInitialization object takes ownership of Initializations pushed
/// here.
SmallVector<InitializationPtr, 4> subInitializations;
TupleInitialization() : Initialization(Initialization::Kind::Tuple) {}
SILValue getAddressOrNull() const override {
if (subInitializations.size() == 1)
return subInitializations[0]->getAddressOrNull();
else
return SILValue();
}
ArrayRef<InitializationPtr> getSubInitializations() const override {
return subInitializations;
}
void finishInitialization(SILGenFunction &gen) override {
for (auto &sub : subInitializations)
sub->finishInitialization(gen);
}
};
class StrongReleaseCleanup : public Cleanup {
SILValue box;
public:
StrongReleaseCleanup(SILValue box) : box(box) {}
void emit(SILGenFunction &gen, CleanupLocation l) override {
gen.B.emitStrongRelease(l, box);
}
};
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.emitDestroyAddr(l, v);
else
gen.B.emitReleaseValueOperation(l, v);
}
};
/// 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);
}
};
/// 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);
}
};
/// 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);
}
};
/// An initialization of a local 'var'.
class LocalVariableInitialization : public SingleBufferInitialization {
/// The local variable decl being initialized.
VarDecl *Var;
SILGenFunction &Gen;
/// 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 *var, SILGenFunction &gen)
: Var(var), Gen(gen) {
// Push a cleanup to destroy the local variable. This has to be
// inactive until the variable is initialized.
gen.Cleanups.pushCleanupInState<DestroyLocalVariable>(CleanupState::Dormant,
var);
ReleaseCleanup = gen.Cleanups.getTopCleanup();
// Push a cleanup to deallocate the local variable.
gen.Cleanups.pushCleanup<DeallocateUninitializedLocalVariable>(var);
DeallocCleanup = gen.Cleanups.getTopCleanup();
}
~LocalVariableInitialization() override {
assert(DidFinish && "did not call VarInit::finishInitialization!");
}
SILValue getAddressOrNull() const override {
assert(Gen.VarLocs.count(Var) && "did not emit var?!");
return Gen.VarLocs[Var].getAddress();
}
void finishInitialization(SILGenFunction &gen) override {
assert(!DidFinish &&
"called LocalVariableInitialization::finishInitialization twice!");
Gen.Cleanups.setCleanupState(DeallocCleanup, CleanupState::Dead);
Gen.Cleanups.setCleanupState(ReleaseCleanup, CleanupState::Active);
DidFinish = true;
}
};
/// 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;
bool DidFinish = false;
public:
LetValueInitialization(VarDecl *vd, bool isArgument, SILGenFunction &gen)
: Initialization(Initialization::Kind::LetValue), vd(vd) {
auto &lowering = gen.getTypeLowering(vd->getType());
// If this is an address-only let declaration for a real let declaration
// (not a function argument), create a buffer to bind the expression value
// assigned into this slot.
bool needsTemporaryBuffer = lowering.isAddressOnly();
// If this is a function argument, we don't usually need a temporary buffer
// because the incoming pointer can be directly bound as our let buffer.
// However, if this VarDecl has tuple type, then it will be passed to the
// SILFunction as multiple SILArguments, and those *do* need to be rebound
// into a temporary buffer.
if (isArgument && !vd->getType()->is<TupleType>())
needsTemporaryBuffer = false;
if (needsTemporaryBuffer) {
address = gen.emitTemporaryAllocation(vd, lowering.getLoweredType());
gen.enterDormantTemporaryCleanup(address, lowering);
gen.VarLocs[vd] = SILGenFunction::VarLoc::getConstant(address);
} else {
// 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();
}
~LetValueInitialization() override {
assert(DidFinish && "did not call LetValueInit::finishInitialization!");
}
void emitDebugValue(SILValue v, SILGenFunction &gen) {
// Emit a debug_value[_addr] instruction to record the start of this value's
// lifetime.
if (!v.getType().isAddress())
gen.B.createDebugValue(vd, v);
else
gen.B.createDebugValueAddr(vd, v);
}
SILValue getAddressOrNull() const override {
// We only have an address for address-only lets.
return address;
}
ArrayRef<InitializationPtr> getSubInitializations() const override {
return {};
}
void bindValue(SILValue value, SILGenFunction &gen) override {
assert(!gen.VarLocs.count(vd) && "Already emitted this vardecl?");
gen.VarLocs[vd] = SILGenFunction::VarLoc::getConstant(value);
emitDebugValue(value, 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!");
gen.Cleanups.setCleanupState(DestroyCleanup, CleanupState::Active);
DidFinish = true;
}
};
/// An initialization for a global variable.
class GlobalInitialization : public SingleBufferInitialization {
/// The physical address of the global.
SILValue address;
public:
GlobalInitialization(SILValue address) : address(address)
{}
SILValue getAddressOrNull() const override {
return address;
}
void finishInitialization(SILGenFunction &gen) override {
// Globals don't need to be cleaned up.
}
};
/// Cleanup that writes back to a inout argument on function exit.
class CleanupWriteBackToInOut : public Cleanup {
VarDecl *var;
SILValue inoutAddr;
public:
CleanupWriteBackToInOut(VarDecl *var, SILValue inoutAddr)
: var(var), inoutAddr(inoutAddr) {}
void emit(SILGenFunction &gen, CleanupLocation l) override {
// Assign from the local variable to the inout address with an
// 'autogenerated' copyaddr.
l.markAutoGenerated();
gen.B.createCopyAddr(l, gen.VarLocs[var].getAddress(), inoutAddr,
IsNotTake, IsNotInitialization);
}
};
/// Initialize a writeback buffer that receives the "in" value of a inout
/// argument on function entry and writes the "out" value back to the inout
/// address on function exit.
class InOutInitialization : public Initialization {
/// The VarDecl for the inout symbol.
VarDecl *vd;
public:
InOutInitialization(VarDecl *vd)
: Initialization(Initialization::Kind::AddressBinding), vd(vd) {}
SILValue getAddressOrNull() const override {
llvm_unreachable("inout argument should be bound by bindAddress");
}
ArrayRef<InitializationPtr> getSubInitializations() const override {
return {};
}
void bindAddress(SILValue address, SILGenFunction &gen,
SILLocation loc) override {
// Allocate the local variable for the inout.
auto initVar = gen.emitLocalVariableWithCleanup(vd);
// Initialize with the value from the inout with an "autogenerated"
// copyaddr.
loc.markAsPrologue();
loc.markAutoGenerated();
gen.B.createCopyAddr(loc, address, initVar->getAddress(),
IsNotTake, IsInitialization);
initVar->finishInitialization(gen);
// Set up a cleanup to write back to the inout.
gen.Cleanups.pushCleanup<CleanupWriteBackToInOut>(vd, address);
}
};
/// Initialize a variable of reference-storage type.
class ReferenceStorageInitialization : public Initialization {
InitializationPtr VarInit;
public:
ReferenceStorageInitialization(InitializationPtr &&subInit)
: Initialization(Initialization::Kind::Translating),
VarInit(std::move(subInit)) {}
ArrayRef<InitializationPtr> getSubInitializations() const override { return {}; }
SILValue getAddressOrNull() const override { return SILValue(); }
void translateValue(SILGenFunction &gen, SILLocation loc,
ManagedValue value) override {
value.forwardInto(gen, loc, VarInit->getAddress());
}
void finishInitialization(SILGenFunction &gen) override {
VarInit->finishInitialization(gen);
}
};
/// InitializationForPattern - A visitor for traversing a pattern, generating
/// SIL code to allocate the declared variables, and generating an
/// Initialization representing the needed initializations.
struct InitializationForPattern
: public PatternVisitor<InitializationForPattern, InitializationPtr>
{
SILGenFunction &Gen;
enum ArgumentOrVar_t { Argument, Var } ArgumentOrVar;
InitializationForPattern(SILGenFunction &Gen, ArgumentOrVar_t ArgumentOrVar)
: Gen(Gen), ArgumentOrVar(ArgumentOrVar) {}
// 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) {
return Gen.emitInitializationForVarDecl(P->getDecl(),
ArgumentOrVar == Argument,
P->hasType() ? P->getType() : Type());
}
// Bind a tuple pattern by aggregating the component variables into a
// TupleInitialization.
InitializationPtr visitTuplePattern(TuplePattern *P) {
TupleInitialization *init = new TupleInitialization();
for (auto &elt : P->getFields())
init->subInitializations.push_back(visit(elt.getPattern()));
return InitializationPtr(init);
}
// TODO: Handle bindings from 'case' labels and match expressions.
#define INVALID_PATTERN(Id, Parent) \
InitializationPtr visit##Id##Pattern(Id##Pattern *) { \
llvm_unreachable("pattern not valid in argument or var binding"); \
}
#define PATTERN(Id, Parent)
#define REFUTABLE_PATTERN(Id, Parent) INVALID_PATTERN(Id, Parent)
#include "swift/AST/PatternNodes.def"
#undef INVALID_PATTERN
};
/// A visitor that marks local variables uninitialized in a pattern binding
/// without an initializer.
struct MarkPatternUninitialized
: public PatternVisitor<MarkPatternUninitialized>
{
SILGenFunction &Gen;
MarkPatternUninitialized(SILGenFunction &Gen) : Gen(Gen) {}
// Paren, Typed, and Var patterns are noops, just look through them.
void visitParenPattern(ParenPattern *P) {
return visit(P->getSubPattern());
}
void visitTypedPattern(TypedPattern *P) {
return visit(P->getSubPattern());
}
void visitVarPattern(VarPattern *P) {
return visit(P->getSubPattern());
}
void visitAnyPattern(AnyPattern *P) {}
void visitTuplePattern(TuplePattern *P) {
for (auto elt : P->getFields())
visit(elt.getPattern());
}
void visitNamedPattern(NamedPattern *P) {
VarDecl *var = P->getDecl();
if (!var->hasStorage())
return;
// Emit a mark_uninitialized for the variable's storage, and fix up the
// loc to refer to the marker.
assert(Gen.VarLocs.count(var)
&& "no varloc for uninitialized var?!");
auto &varLoc = Gen.VarLocs[var];
assert(varLoc.isAddress()
&& "uninitialized var doesn't have an address?!");
auto mu
= Gen.B.createMarkUninitializedVar(P->getDecl(), varLoc.getAddress());
Gen.VarLocs[var] = SILGenFunction::VarLoc::getAddress(mu, varLoc.box);
}
// TODO: Handle bindings from 'case' labels and match expressions.
#define INVALID_PATTERN(Id, Parent) \
void visit##Id##Pattern(Id##Pattern *) { \
llvm_unreachable("pattern not valid in argument or var binding"); \
}
#define PATTERN(Id, Parent)
#define REFUTABLE_PATTERN(Id, Parent) INVALID_PATTERN(Id, Parent)
#include "swift/AST/PatternNodes.def"
#undef INVALID_PATTERN
};
} // end anonymous namespace
InitializationPtr
SILGenFunction::emitInitializationForVarDecl(VarDecl *vd, bool isArgument,
Type patternType) {
// If this is a computed variable, we don't need to do anything here.
// We'll generate the getter and setter when we see their FuncDecls.
if (!vd->hasStorage())
return InitializationPtr(new BlackHoleInitialization());
// If this is a global variable, initialize it without allocations or
// cleanups.
if (!vd->getDeclContext()->isLocalContext()) {
SILValue addr = B.createGlobalAddr(vd, vd,
getLoweredType(vd->getType()).getAddressType());
VarLocs[vd] = SILGenFunction::VarLoc::getAddress(addr);
return InitializationPtr(new GlobalInitialization(addr));
}
CanType varType = vd->getType()->getCanonicalType();
// If this is an inout parameter, set up the writeback variable.
if (isa<InOutType>(varType))
return InitializationPtr(new InOutInitialization(vd));
// If this is a 'let' initialization for a non-address-only type, set up a
// let binding, which stores the initialization value into VarLocs directly.
if (vd->isLet())
return InitializationPtr(new LetValueInitialization(vd, isArgument, *this));
// Otherwise, we have a normal local-variable initialization.
auto varInit = emitLocalVariableWithCleanup(vd);
// Initializing a @weak or @unowned variable requires a change in type.
if (isa<ReferenceStorageType>(varType))
return InitializationPtr(new ReferenceStorageInitialization(
std::move(varInit)));
// Otherwise, the pattern type should match the type of the variable.
// FIXME: why do we ever get patterns without types here?
assert(!patternType || varType == patternType->getCanonicalType());
return varInit;
}
void SILGenFunction::visitPatternBindingDecl(PatternBindingDecl *D) {
// Allocate the variables and build up an Initialization over their
// allocated storage.
InitializationPtr initialization =
InitializationForPattern(*this, InitializationForPattern::Var)
.visit(D->getPattern());
// If an initial value expression was specified by the decl, emit it into
// the initialization. Otherwise, mark it uninitialized for DI to resolve.
if (D->getInit()) {
FullExpr Scope(Cleanups, CleanupLocation(D->getInit()));
emitExprInto(D->getInit(), initialization.get());
} else {
initialization->finishInitialization(*this);
MarkPatternUninitialized(*this).visit(D->getPattern());
}
}
InitializationPtr
SILGenFunction::emitPatternBindingInitialization(Pattern *P) {
return InitializationForPattern(*this, InitializationForPattern::Var)
.visit(P);
}
/// Enter a cleanup to deallocate the given location.
CleanupHandle SILGenFunction::enterDeallocStackCleanup(SILValue temp) {
assert(temp.getType().isLocalStorage() &&
"must deallocate container operand, not address operand!");
Cleanups.pushCleanup<DeallocStackCleanup>(temp);
return Cleanups.getTopCleanup();
}
CleanupHandle SILGenFunction::enterDestroyCleanup(SILValue valueOrAddr) {
Cleanups.pushCleanup<ReleaseValueCleanup>(valueOrAddr);
return Cleanups.getTopCleanup();
}
namespace {
/// A visitor for traversing a pattern, creating
/// SILArguments, and initializing the local value for each pattern variable
/// in a function argument list.
struct ArgumentInitVisitor :
public PatternVisitor<ArgumentInitVisitor, /*RetTy=*/ void,
/*Args...=*/ Initialization*>
{
SILGenFunction &gen;
SILFunction &f;
SILBuilder &initB;
ArgumentInitVisitor(SILGenFunction &gen, SILFunction &f)
: gen(gen), f(f), initB(gen.B) {}
RValue makeArgument(Type ty, SILBasicBlock *parent, SILLocation l) {
assert(ty && "no type?!");
return RValue::emitBBArguments(ty->getCanonicalType(), gen, parent, l);
}
/// Create a SILArgument and store its value into the given Initialization,
/// if not null.
void makeArgumentInto(Type ty, SILBasicBlock *parent,
SILLocation loc, Initialization *I) {
assert(I && "no initialization?");
assert(ty && "no type?!");
loc.markAsPrologue();
RValue argrv = makeArgument(ty, parent, loc);
if (I->kind == Initialization::Kind::AddressBinding) {
SILValue arg = std::move(argrv).forwardAsSingleValue(gen, loc);
I->bindAddress(arg, gen, loc);
// If this is an address-only non-inout argument, we take ownership
// of the referenced value.
if (!ty->is<InOutType>())
gen.enterDestroyCleanup(arg);
I->finishInitialization(gen);
} else {
std::move(argrv).forwardInto(gen, I, loc);
}
}
// Paren, Typed, and Var patterns are no-ops. Just look through them.
void visitParenPattern(ParenPattern *P, Initialization *I) {
visit(P->getSubPattern(), I);
}
void visitTypedPattern(TypedPattern *P, Initialization *I) {
visit(P->getSubPattern(), I);
}
void visitVarPattern(VarPattern *P, Initialization *I) {
visit(P->getSubPattern(), I);
}
void visitTuplePattern(TuplePattern *P, Initialization *I) {
// If the tuple is empty, so should be our initialization. Just pass an
// empty tuple upwards.
if (P->getFields().empty()) {
switch (I->kind) {
case Initialization::Kind::Ignored:
break;
case Initialization::Kind::Tuple:
assert(I->getSubInitializations().empty() &&
"empty tuple pattern with non-empty-tuple initializer?!");
break;
case Initialization::Kind::AddressBinding:
llvm_unreachable("empty tuple pattern with inout initializer?!");
case Initialization::Kind::LetValue:
llvm_unreachable("empty tuple pattern with letvalue initializer?!");
case Initialization::Kind::Translating:
llvm_unreachable("empty tuple pattern with translating initializer?!");
case Initialization::Kind::SingleBuffer:
assert(I->getAddress().getType().getSwiftRValueType()
== P->getType()->getCanonicalType()
&& "empty tuple pattern with non-empty-tuple initializer?!");
break;
}
return;
}
// Destructure the initialization into per-element Initializations.
SmallVector<InitializationPtr, 2> buf;
ArrayRef<InitializationPtr> subInits =
I->getSubInitializationsForTuple(gen, P->getType()->getCanonicalType(),
buf, RegularLocation(P));
assert(P->getFields().size() == subInits.size() &&
"TupleInitialization size does not match tuple pattern size!");
for (size_t i = 0, size = P->getFields().size(); i < size; ++i)
visit(P->getFields()[i].getPattern(), subInits[i].get());
}
void visitAnyPattern(AnyPattern *P, Initialization *I) {
// A value bound to _ is unused and can be immediately released.
assert(I->kind == Initialization::Kind::Ignored &&
"any pattern should match a black-hole Initialization");
auto &lowering = gen.getTypeLowering(P->getType());
auto &AC = gen.getASTContext();
auto VD = new (AC) VarDecl(/*static*/ false, /*IsLet*/ true, SourceLoc(),
// FIXME: we should probably number them.
AC.getIdentifier("_"), P->getType(),
f.getDeclContext());
SILValue arg =
makeArgument(P->getType(), f.begin(), VD).forwardAsSingleValue(gen, VD);
lowering.emitDestroyRValue(gen.B, P, arg);
}
void visitNamedPattern(NamedPattern *P, Initialization *I) {
makeArgumentInto(P->getType(), f.begin(), P->getDecl(), I);
}
#define PATTERN(Id, Parent)
#define REFUTABLE_PATTERN(Id, Parent) \
void visit##Id##Pattern(Id##Pattern *, Initialization *) { \
llvm_unreachable("pattern not valid in argument binding"); \
}
#include "swift/AST/PatternNodes.def"
};
/// Tuple values captured by a closure are passed as individual arguments to the
/// SILFunction since SILFunctionType canonicalizes away tuple types.
static SILValue
emitReconstitutedConstantCaptureArguments(SILType ty,
ValueDecl *capture,
SILGenFunction &gen) {
auto TT = ty.getAs<TupleType>();
if (!TT)
return new (gen.SGM.M) SILArgument(ty, gen.F.begin(), capture);
SmallVector<SILValue, 4> Elts;
for (unsigned i = 0, e = TT->getNumElements(); i != e; ++i) {
auto EltTy = ty.getTupleElementType(i);
auto EV =
emitReconstitutedConstantCaptureArguments(EltTy, capture, gen);
Elts.push_back(EV);
}
return gen.B.createTuple(capture, ty, Elts);
}
static void emitCaptureArguments(SILGenFunction &gen,
CaptureInfo::LocalCaptureTy capture) {
ASTContext &c = gen.getASTContext();
auto *VD = capture.getPointer();
auto type = VD->getType();
switch (getDeclCaptureKind(capture)) {
case CaptureKind::None:
break;
case CaptureKind::Constant: {
if (!gen.getTypeLowering(VD->getType()).isAddressOnly()) {
// Constant decls are captured by value. If the captured value is a tuple
// value, we need to reconstitute it before sticking it in VarLocs.
SILType ty = gen.getLoweredType(VD->getType());
SILValue val = emitReconstitutedConstantCaptureArguments(ty, VD, gen);
gen.VarLocs[VD] = SILGenFunction::VarLoc::getConstant(val);
gen.enterDestroyCleanup(val);
break;
}
// Address-only values we capture by-box since partial_apply doesn't work
// with @in for address-only types.
SWIFT_FALLTHROUGH;
}
case CaptureKind::Box: {
// LValues are captured as two arguments: a retained ObjectPointer that owns
// the captured value, and the address of the value itself.
SILType ty = gen.getLoweredType(type).getAddressType();
SILValue box = new (gen.SGM.M) SILArgument(SILType::getObjectPointerType(c),
gen.F.begin(), VD);
SILValue addr = new (gen.SGM.M) SILArgument(ty, gen.F.begin(), VD);
gen.VarLocs[VD] = SILGenFunction::VarLoc::getAddress(addr, box);
gen.Cleanups.pushCleanup<StrongReleaseCleanup>(box);
break;
}
case CaptureKind::LocalFunction: {
// Local functions are captured by value.
assert(!type->is<LValueType>() && !type->is<InOutType>() &&
"capturing inout by value?!");
const TypeLowering &ti = gen.getTypeLowering(type);
SILValue value = new (gen.SGM.M) SILArgument(ti.getLoweredType(),
gen.F.begin(), VD);
gen.LocalFunctions[SILDeclRef(VD)] = value;
gen.enterDestroyCleanup(value);
break;
}
case CaptureKind::GetterSetter: {
// Capture the setter and getter closures by value.
Type setTy = cast<AbstractStorageDecl>(VD)->getSetter()->getType();
SILType lSetTy = gen.getLoweredType(setTy);
SILValue value = new (gen.SGM.M) SILArgument(lSetTy, gen.F.begin(), VD);
gen.LocalFunctions[SILDeclRef(cast<AbstractStorageDecl>(VD)->getSetter(),
SILDeclRef::Kind::Func)] = value;
gen.enterDestroyCleanup(value);
SWIFT_FALLTHROUGH;
}
case CaptureKind::Getter: {
// Capture the getter closure by value.
Type getTy = cast<AbstractStorageDecl>(VD)->getGetter()->getType();
SILType lGetTy = gen.getLoweredType(getTy);
SILValue value = new (gen.SGM.M) SILArgument(lGetTy, gen.F.begin(), VD);
gen.LocalFunctions[SILDeclRef(cast<AbstractStorageDecl>(VD)->getGetter(),
SILDeclRef::Kind::Func)] = value;
gen.enterDestroyCleanup(value);
break;
}
}
}
} // end anonymous namespace
void SILGenFunction::emitProlog(AnyFunctionRef TheClosure,
ArrayRef<Pattern *> paramPatterns,
Type resultType) {
emitProlog(paramPatterns, resultType, TheClosure.getAsDeclContext());
// Emit the capture argument variables. These are placed last because they
// become the first curry level of the SIL function.
SmallVector<CaptureInfo::LocalCaptureTy, 4> LocalCaptures;
TheClosure.getLocalCaptures(LocalCaptures);
for (auto capture : LocalCaptures)
emitCaptureArguments(*this, capture);
}
void SILGenFunction::emitProlog(ArrayRef<Pattern *> paramPatterns,
Type resultType, DeclContext *DeclCtx) {
// If the return type is address-only, emit the indirect return argument.
const TypeLowering &returnTI = getTypeLowering(resultType);
if (returnTI.isReturnedIndirectly()) {
auto &AC = getASTContext();
auto VD = new (AC) VarDecl(/*static*/ false, /*IsLet*/ false, SourceLoc(),
AC.getIdentifier("$return_value"), resultType,
DeclCtx);
IndirectReturnAddress = new (SGM.M)
SILArgument(returnTI.getLoweredType(), F.begin(), VD);
}
// Emit the argument variables in calling convention order.
for (Pattern *p : reversed(paramPatterns)) {
// Allocate the local mutable argument storage and set up an Initialization.
InitializationPtr argInit
= InitializationForPattern(*this, InitializationForPattern::Argument)
.visit(p);
// Add the SILArguments and use them to initialize the local argument
// values.
ArgumentInitVisitor(*this, F).visit(p, argInit.get());
}
}
SILValue SILGenFunction::emitSelfDecl(VarDecl *selfDecl) {
// Emit the implicit 'self' argument.
SILType selfType = getLoweredLoadableType(selfDecl->getType());
SILValue selfValue = new (SGM.M) SILArgument(selfType, F.begin(), selfDecl);
VarLocs[selfDecl] = VarLoc::getConstant(selfValue);
B.createDebugValue(selfDecl, selfValue);
return selfValue;
}
void SILGenFunction::prepareEpilog(Type resultType, CleanupLocation CleanupL) {
auto *epilogBB = createBasicBlock();
// If we have a non-null, non-void, non-address-only return type, receive the
// return value via a BB argument.
NeedsReturn = resultType && !resultType->isVoid();
if (NeedsReturn) {
auto &resultTI = getTypeLowering(resultType);
if (!resultTI.isAddressOnly())
new (F.getModule()) SILArgument(resultTI.getLoweredType(), epilogBB);
}
ReturnDest = JumpDest(epilogBB, getCleanupsDepth(), CleanupL);
}
bool SILGenModule::requiresObjCMethodEntryPoint(FuncDecl *method) {
// Property accessors should be generated alongside the property.
if (method->isGetterOrSetter())
return method->getAccessorStorageDecl()->usesObjCGetterAndSetter();
if (method->isObjC() || method->getAttrs().isIBAction())
return true;
if (auto override = method->getOverriddenDecl())
return requiresObjCMethodEntryPoint(override);
return false;
}
bool SILGenModule::requiresObjCMethodEntryPoint(ConstructorDecl *constructor) {
return constructor->isObjC();
}
bool SILGenModule::requiresObjCDispatch(ValueDecl *vd) {
if (auto *fd = dyn_cast<FuncDecl>(vd)) {
// If a function has an associated Clang node, it's foreign.
if (vd->hasClangNode())
return true;
return requiresObjCMethodEntryPoint(fd);
}
if (auto *cd = dyn_cast<ConstructorDecl>(vd))
return requiresObjCMethodEntryPoint(cd);
if (auto *asd = dyn_cast<AbstractStorageDecl>(vd))
return asd->usesObjCGetterAndSetter();
return vd->isObjC();
}
bool SILGenModule::requiresObjCSuperDispatch(ValueDecl *vd) {
return requiresObjCDispatch(vd);
}
/// An ASTVisitor for populating SILVTable entries from ClassDecl members.
class SILGenVTable : public Lowering::ASTVisitor<SILGenVTable> {
public:
SILGenModule &SGM;
ClassDecl *theClass;
std::vector<SILVTable::Pair> vtableEntries;
SILGenVTable(SILGenModule &SGM, ClassDecl *theClass)
: SGM(SGM), theClass(theClass)
{
// Populate the superclass members, if any.
Type super = theClass->getSuperclass();