-
Notifications
You must be signed in to change notification settings - Fork 10.4k
/
Copy pathSILGenBuiltin.cpp
2255 lines (1941 loc) · 98.2 KB
/
SILGenBuiltin.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
//===--- SILGenBuiltin.cpp - SIL generation for builtin call sites -------===//
//
// 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 "SpecializedEmitter.h"
#include "ArgumentSource.h"
#include "Cleanup.h"
#include "Conversion.h"
#include "Initialization.h"
#include "LValue.h"
#include "RValue.h"
#include "Scope.h"
#include "SILGenFunction.h"
#include "swift/AST/ASTContext.h"
#include "swift/AST/Builtins.h"
#include "swift/AST/DiagnosticsSIL.h"
#include "swift/AST/DistributedDecl.h"
#include "swift/AST/FileUnit.h"
#include "swift/AST/GenericEnvironment.h"
#include "swift/AST/Module.h"
#include "swift/AST/ProtocolConformance.h"
#include "swift/AST/ReferenceCounting.h"
#include "swift/Basic/Assertions.h"
#include "swift/SIL/SILArgument.h"
#include "swift/SIL/SILUndef.h"
#include "swift/AST/TypeCheckRequests.h" // FIXME: Temporary
#include "swift/AST/NameLookupRequests.h" // FIXME: Temporary
using namespace swift;
using namespace Lowering;
/// Break down an expression that's the formal argument expression to
/// a builtin function, returning its individualized arguments.
///
/// Because these are builtin operations, we can make some structural
/// assumptions about the expression used to call them.
static std::optional<SmallVector<Expr *, 2>>
decomposeArguments(SILGenFunction &SGF, SILLocation loc,
PreparedArguments &&args, unsigned expectedCount) {
SmallVector<Expr*, 2> result;
auto sources = std::move(args).getSources();
if (sources.size() == expectedCount) {
for (auto &&source : sources)
result.push_back(std::move(source).asKnownExpr());
return result;
}
SGF.SGM.diagnose(loc, diag::invalid_sil_builtin,
"argument to builtin should be a literal tuple");
return std::nullopt;
}
static ManagedValue emitBuiltinRetain(SILGenFunction &SGF,
SILLocation loc,
SubstitutionMap substitutions,
ArrayRef<ManagedValue> args,
SGFContext C) {
// The value was produced at +1; we can produce an unbalanced retain simply by
// disabling the cleanup. But this would violate ownership semantics. Instead,
// we must allow for the cleanup and emit a new unmanaged retain value.
SGF.B.createUnmanagedRetainValue(loc, args[0].getValue(),
SGF.B.getDefaultAtomicity());
return ManagedValue::forObjectRValueWithoutOwnership(SGF.emitEmptyTuple(loc));
}
static ManagedValue emitBuiltinRelease(SILGenFunction &SGF,
SILLocation loc,
SubstitutionMap substitutions,
ArrayRef<ManagedValue> args,
SGFContext C) {
// The value was produced at +1, so to produce an unbalanced
// release we need to leave the cleanup intact and then do a *second*
// release.
SGF.B.createUnmanagedReleaseValue(loc, args[0].getValue(),
SGF.B.getDefaultAtomicity());
return ManagedValue::forObjectRValueWithoutOwnership(SGF.emitEmptyTuple(loc));
}
static ManagedValue emitBuiltinAutorelease(SILGenFunction &SGF,
SILLocation loc,
SubstitutionMap substitutions,
ArrayRef<ManagedValue> args,
SGFContext C) {
SGF.B.createUnmanagedAutoreleaseValue(loc, args[0].getValue(),
SGF.B.getDefaultAtomicity());
return ManagedValue::forObjectRValueWithoutOwnership(SGF.emitEmptyTuple(loc));
}
/// Specialized emitter for Builtin.load and Builtin.take.
static ManagedValue emitBuiltinLoadOrTake(SILGenFunction &SGF,
SILLocation loc,
SubstitutionMap substitutions,
ArrayRef<ManagedValue> args,
SGFContext C,
IsTake_t isTake,
bool isStrict,
bool isInvariant,
llvm::MaybeAlign align) {
assert(substitutions.getReplacementTypes().size() == 1 &&
"load should have single substitution");
assert(args.size() == 1 && "load should have a single argument");
// The substitution gives the type of the load. This is always a
// first-class type; there is no way to e.g. produce a @weak load
// with this builtin.
auto &rvalueTL = SGF.getTypeLowering(substitutions.getReplacementTypes()[0]);
SILType loadedType = rvalueTL.getLoweredType();
// Convert the pointer argument to a SIL address.
//
// Default to an unaligned pointer. This can be optimized in the presence of
// Builtin.assumeAlignment.
SILValue addr = SGF.B.createPointerToAddress(loc, args[0].getUnmanagedValue(),
loadedType.getAddressType(),
isStrict, isInvariant, align);
// Perform the load.
return SGF.emitLoad(loc, addr, rvalueTL, C, isTake);
}
static ManagedValue emitBuiltinLoad(SILGenFunction &SGF,
SILLocation loc,
SubstitutionMap substitutions,
ArrayRef<ManagedValue> args,
SGFContext C) {
// Regular loads assume natural alignment.
return emitBuiltinLoadOrTake(SGF, loc, substitutions, args,
C, IsNotTake,
/*isStrict*/ true, /*isInvariant*/ false,
llvm::MaybeAlign());
}
static ManagedValue emitBuiltinLoadRaw(SILGenFunction &SGF,
SILLocation loc,
SubstitutionMap substitutions,
ArrayRef<ManagedValue> args,
SGFContext C) {
// Raw loads cannot assume alignment.
return emitBuiltinLoadOrTake(SGF, loc, substitutions, args,
C, IsNotTake,
/*isStrict*/ false, /*isInvariant*/ false,
llvm::MaybeAlign(1));
}
static ManagedValue emitBuiltinLoadInvariant(SILGenFunction &SGF,
SILLocation loc,
SubstitutionMap substitutions,
ArrayRef<ManagedValue> args,
SGFContext C) {
// Regular loads assume natural alignment.
return emitBuiltinLoadOrTake(SGF, loc, substitutions, args,
C, IsNotTake,
/*isStrict*/ false, /*isInvariant*/ true,
llvm::MaybeAlign());
}
static ManagedValue emitBuiltinTake(SILGenFunction &SGF,
SILLocation loc,
SubstitutionMap substitutions,
ArrayRef<ManagedValue> args,
SGFContext C) {
// Regular loads assume natural alignment.
return emitBuiltinLoadOrTake(SGF, loc, substitutions, args,
C, IsTake,
/*isStrict*/ true, /*isInvariant*/ false,
llvm::MaybeAlign());
}
/// Specialized emitter for Builtin.destroy.
static ManagedValue emitBuiltinDestroy(SILGenFunction &SGF,
SILLocation loc,
SubstitutionMap substitutions,
ArrayRef<ManagedValue> args,
SGFContext C) {
assert(args.size() == 2 && "destroy should have two arguments");
assert(substitutions.getReplacementTypes().size() == 1 &&
"destroy should have a single substitution");
// The substitution determines the type of the thing we're destroying.
auto &ti = SGF.getTypeLowering(substitutions.getReplacementTypes()[0]);
// Destroy is a no-op for trivial types.
if (ti.isTrivial())
return ManagedValue::forObjectRValueWithoutOwnership(
SGF.emitEmptyTuple(loc));
SILType destroyType = ti.getLoweredType();
// Convert the pointer argument to a SIL address.
SILValue addr =
SGF.B.createPointerToAddress(loc, args[1].getUnmanagedValue(),
destroyType.getAddressType(),
/*isStrict*/ true,
/*isInvariant*/ false);
// Destroy the value indirectly. Canonicalization will promote to loads
// and releases if appropriate.
SGF.B.createDestroyAddr(loc, addr);
return ManagedValue::forObjectRValueWithoutOwnership(SGF.emitEmptyTuple(loc));
}
static ManagedValue emitBuiltinStore(SILGenFunction &SGF, SILLocation loc,
SubstitutionMap substitutions,
ArrayRef<ManagedValue> args, SGFContext C,
bool isStrict, bool isInvariant,
llvm::MaybeAlign alignment) {
assert(args.size() >= 2 && "should have two arguments");
assert(substitutions.getReplacementTypes().size() == 1 &&
"should have a single substitution");
// The substitution determines the type of the thing we're destroying.
CanType formalTy = substitutions.getReplacementTypes()[0]->getCanonicalType();
SILType loweredTy = SGF.getLoweredType(formalTy);
// Convert the destination pointer argument to a SIL address.
SILValue addr = SGF.B.createPointerToAddress(
loc, args.back().getUnmanagedValue(), loweredTy.getAddressType(),
isStrict, isInvariant, alignment);
// Build the value to be stored, reconstructing tuples if needed.
auto src = RValue(SGF, args.slice(0, args.size() - 1), formalTy);
std::move(src).ensurePlusOne(SGF, loc).assignInto(SGF, loc, addr);
return ManagedValue::forObjectRValueWithoutOwnership(SGF.emitEmptyTuple(loc));
}
static ManagedValue emitBuiltinAssign(SILGenFunction &SGF, SILLocation loc,
SubstitutionMap substitutions,
ArrayRef<ManagedValue> args,
SGFContext C) {
return emitBuiltinStore(SGF, loc, substitutions, args, C, /*isStrict=*/true,
/*isInvariant=*/false, llvm::MaybeAlign());
}
static ManagedValue emitBuiltinStoreRaw(SILGenFunction &SGF, SILLocation loc,
SubstitutionMap substitutions,
ArrayRef<ManagedValue> args,
SGFContext C) {
return emitBuiltinStore(SGF, loc, substitutions, args, C, /*isStrict=*/false,
/*isInvariant=*/false, llvm::MaybeAlign(1));
}
/// Emit Builtin.initialize by evaluating the operand directly into
/// the address.
static ManagedValue emitBuiltinInit(SILGenFunction &SGF,
SILLocation loc,
SubstitutionMap substitutions,
PreparedArguments &&preparedArgs,
SGFContext C) {
auto argsOrError = decomposeArguments(SGF, loc, std::move(preparedArgs), 2);
if (!argsOrError)
return ManagedValue::forObjectRValueWithoutOwnership(
SGF.emitEmptyTuple(loc));
auto args = *argsOrError;
CanType formalType =
substitutions.getReplacementTypes()[0]->getCanonicalType();
auto &formalTL = SGF.getTypeLowering(formalType);
SILValue addr = SGF.emitRValueAsSingleValue(args[1]).getUnmanagedValue();
addr = SGF.B.createPointerToAddress(
loc, addr, formalTL.getLoweredType().getAddressType(),
/*isStrict*/ true,
/*isInvariant*/ false);
TemporaryInitialization init(addr, CleanupHandle::invalid());
SGF.emitExprInto(args[0], &init);
return ManagedValue::forObjectRValueWithoutOwnership(SGF.emitEmptyTuple(loc));
}
/// Specialized emitter for Builtin.fixLifetime.
static ManagedValue emitBuiltinFixLifetime(SILGenFunction &SGF,
SILLocation loc,
SubstitutionMap substitutions,
ArrayRef<ManagedValue> args,
SGFContext C) {
for (auto arg : args) {
SGF.B.createFixLifetime(loc, arg.getValue());
}
return ManagedValue::forObjectRValueWithoutOwnership(SGF.emitEmptyTuple(loc));
}
static ManagedValue emitCastToReferenceType(SILGenFunction &SGF,
SILLocation loc,
SubstitutionMap substitutions,
ArrayRef<ManagedValue> args,
SGFContext C,
SILType objPointerType) {
assert(args.size() == 1 && "cast should have a single argument");
assert(substitutions.getReplacementTypes().size() == 1 &&
"cast should have a type substitution");
// Bail if the source type is not a class reference of some kind.
Type argTy = substitutions.getReplacementTypes()[0];
if (!argTy->mayHaveSuperclass() && !argTy->isClassExistentialType()) {
SGF.SGM.diagnose(loc, diag::invalid_sil_builtin,
"castToNativeObject source must be a class");
return SGF.emitUndef(objPointerType);
}
// Grab the argument.
ManagedValue arg = args[0];
// If the argument is existential, open it.
if (argTy->isClassExistentialType()) {
auto openedTy =
ExistentialArchetypeType::get(argTy->getCanonicalType());
SILType loweredOpenedTy = SGF.getLoweredLoadableType(openedTy);
arg = SGF.B.createOpenExistentialRef(loc, arg, loweredOpenedTy);
}
// Return the cast result.
return SGF.B.createUncheckedRefCast(loc, arg, objPointerType);
}
/// Specialized emitter for Builtin.unsafeCastToNativeObject.
static ManagedValue emitBuiltinUnsafeCastToNativeObject(SILGenFunction &SGF,
SILLocation loc,
SubstitutionMap substitutions,
ArrayRef<ManagedValue> args,
SGFContext C) {
return emitCastToReferenceType(SGF, loc, substitutions, args, C,
SILType::getNativeObjectType(SGF.F.getASTContext()));
}
/// Specialized emitter for Builtin.castToNativeObject.
static ManagedValue emitBuiltinCastToNativeObject(SILGenFunction &SGF,
SILLocation loc,
SubstitutionMap substitutions,
ArrayRef<ManagedValue> args,
SGFContext C) {
auto ty = args[0].getType().getASTType();
(void)ty;
assert(ty->getReferenceCounting() == ReferenceCounting::Native &&
"Can only cast types that use native reference counting to native "
"object");
return emitBuiltinUnsafeCastToNativeObject(SGF, loc, substitutions,
args, C);
}
static ManagedValue emitCastFromReferenceType(SILGenFunction &SGF,
SILLocation loc,
SubstitutionMap substitutions,
ArrayRef<ManagedValue> args,
SGFContext C) {
assert(args.size() == 1 && "cast should have a single argument");
assert(substitutions.getReplacementTypes().size() == 1 &&
"cast should have a single substitution");
// The substitution determines the destination type.
SILType destType =
SGF.getLoweredType(substitutions.getReplacementTypes()[0]);
// Bail if the source type is not a class reference of some kind.
if (!substitutions.getReplacementTypes()[0]->isBridgeableObjectType()
|| !destType.isObject()) {
SGF.SGM.diagnose(loc, diag::invalid_sil_builtin,
"castFromNativeObject dest must be an object type");
// Recover by propagating an undef result.
return SGF.emitUndef(destType);
}
return SGF.B.createUncheckedRefCast(loc, args[0], destType);
}
/// Specialized emitter for Builtin.castFromNativeObject.
static ManagedValue emitBuiltinCastFromNativeObject(SILGenFunction &SGF,
SILLocation loc,
SubstitutionMap substitutions,
ArrayRef<ManagedValue> args,
SGFContext C) {
return emitCastFromReferenceType(SGF, loc, substitutions, args, C);
}
/// Specialized emitter for Builtin.bridgeToRawPointer.
static ManagedValue emitBuiltinBridgeToRawPointer(SILGenFunction &SGF,
SILLocation loc,
SubstitutionMap substitutions,
ArrayRef<ManagedValue> args,
SGFContext C) {
assert(args.size() == 1 && "bridge should have a single argument");
// Take the reference type argument and cast it to RawPointer.
// RawPointers do not have ownership semantics, so the cleanup on the
// argument remains.
SILType rawPointerType = SILType::getRawPointerType(SGF.F.getASTContext());
SILValue result = SGF.B.createRefToRawPointer(loc, args[0].getValue(),
rawPointerType);
return ManagedValue::forObjectRValueWithoutOwnership(result);
}
/// Specialized emitter for Builtin.bridgeFromRawPointer.
static ManagedValue emitBuiltinBridgeFromRawPointer(SILGenFunction &SGF,
SILLocation loc,
SubstitutionMap substitutions,
ArrayRef<ManagedValue> args,
SGFContext C) {
assert(substitutions.getReplacementTypes().size() == 1 &&
"bridge should have a single substitution");
assert(args.size() == 1 && "bridge should have a single argument");
// The substitution determines the destination type.
// FIXME: Archetype destination type?
auto &destLowering =
SGF.getTypeLowering(substitutions.getReplacementTypes()[0]);
assert(destLowering.isLoadable());
SILType destType = destLowering.getLoweredType();
// Take the raw pointer argument and cast it to the destination type.
SILValue result = SGF.B.createRawPointerToRef(loc, args[0].getUnmanagedValue(),
destType);
// The result has ownership semantics, so retain it with a cleanup.
return SGF.emitManagedCopy(loc, result, destLowering);
}
static ManagedValue emitBuiltinAddressOfBuiltins(SILGenFunction &SGF,
SILLocation loc,
SubstitutionMap substitutions,
PreparedArguments &&preparedArgs,
SGFContext C, bool stackProtected) {
SILType rawPointerType = SILType::getRawPointerType(SGF.getASTContext());
auto argsOrError = decomposeArguments(SGF, loc, std::move(preparedArgs), 1);
if (!argsOrError)
return SGF.emitUndef(rawPointerType);
auto argument = (*argsOrError)[0];
// If the argument is inout, try forming its lvalue. This builtin only works
// if it's trivially physically projectable.
auto inout = cast<InOutExpr>(argument->getSemanticsProvidingExpr());
auto lv = SGF.emitLValue(inout->getSubExpr(), SGFAccessKind::ReadWrite);
if (!lv.isPhysical() || !lv.isLoadingPure()) {
SGF.SGM.diagnose(argument->getLoc(), diag::non_physical_addressof);
return SGF.emitUndef(rawPointerType);
}
auto addr = SGF.emitAddressOfLValue(argument, std::move(lv))
.getLValueAddress();
// Take the address argument and cast it to RawPointer.
SILValue result = SGF.B.createAddressToPointer(loc, addr, rawPointerType,
stackProtected);
return ManagedValue::forObjectRValueWithoutOwnership(result);
}
/// Specialized emitter for Builtin.addressof.
static ManagedValue emitBuiltinAddressOf(SILGenFunction &SGF,
SILLocation loc,
SubstitutionMap substitutions,
PreparedArguments &&preparedArgs,
SGFContext C) {
return emitBuiltinAddressOfBuiltins(SGF, loc, substitutions, std::move(preparedArgs), C,
/*stackProtected=*/ true);
}
static ManagedValue emitBuiltinUnprotectedAddressOf(SILGenFunction &SGF,
SILLocation loc,
SubstitutionMap substitutions,
PreparedArguments &&preparedArgs,
SGFContext C) {
return emitBuiltinAddressOfBuiltins(SGF, loc, substitutions, std::move(preparedArgs), C,
/*stackProtected=*/ false);
}
/// Specialized emitter for Builtin.addressOfBorrow.
static ManagedValue emitBuiltinAddressOfBorrowBuiltins(SILGenFunction &SGF,
SILLocation loc,
SubstitutionMap substitutions,
PreparedArguments &&preparedArgs,
SGFContext C, bool stackProtected) {
SILType rawPointerType = SILType::getRawPointerType(SGF.getASTContext());
auto argsOrError = decomposeArguments(SGF, loc, std::move(preparedArgs), 1);
if (!argsOrError)
return SGF.emitUndef(rawPointerType);
auto argument = (*argsOrError)[0];
SILValue addr;
// Try to borrow the argument at +0 indirect.
// If the argument is a reference to a borrowed addressable parameter, then
// use that parameter's stable address.
if (auto addressableAddr = SGF.tryEmitAddressableParameterAsAddress(
ArgumentSource(argument),
ValueOwnership::Shared)) {
addr = addressableAddr.getValue();
} else {
// We otherwise only support the builtin applied to values that
// are naturally emitted borrowed in memory. (But it would probably be good
// to phase this out since it's not really well-defined how long
// the resulting pointer is good for without something like addressability.)
auto borrow = SGF.emitRValue(argument, SGFContext::AllowGuaranteedPlusZero)
.getAsSingleValue(SGF, argument);
if (!SGF.F.getConventions().useLoweredAddresses()) {
auto &context = SGF.getASTContext();
auto identifier =
stackProtected
? context.getIdentifier("addressOfBorrowOpaque")
: context.getIdentifier("unprotectedAddressOfBorrowOpaque");
auto builtin = SGF.B.createBuiltin(loc, identifier, rawPointerType,
substitutions, {borrow.getValue()});
return ManagedValue::forObjectRValueWithoutOwnership(builtin);
}
if (!borrow.isPlusZero() || !borrow.getType().isAddress()) {
SGF.SGM.diagnose(argument->getLoc(), diag::non_borrowed_indirect_addressof);
return SGF.emitUndef(rawPointerType);
}
addr = borrow.getValue();
}
// Take the address argument and cast it to RawPointer.
SILValue result = SGF.B.createAddressToPointer(loc, addr, rawPointerType,
stackProtected);
return ManagedValue::forObjectRValueWithoutOwnership(result);
}
/// Specialized emitter for Builtin.addressOfBorrow.
static ManagedValue emitBuiltinAddressOfBorrow(SILGenFunction &SGF,
SILLocation loc,
SubstitutionMap substitutions,
PreparedArguments &&preparedArgs,
SGFContext C) {
return emitBuiltinAddressOfBorrowBuiltins(SGF, loc, substitutions,
std::move(preparedArgs), C, /*stackProtected=*/ true);
}
/// Specialized emitter for Builtin.addressOfBorrow.
static ManagedValue emitBuiltinUnprotectedAddressOfBorrow(SILGenFunction &SGF,
SILLocation loc,
SubstitutionMap substitutions,
PreparedArguments &&preparedArgs,
SGFContext C) {
return emitBuiltinAddressOfBorrowBuiltins(SGF, loc, substitutions,
std::move(preparedArgs), C, /*stackProtected=*/ false);
}
/// Specialized emitter for Builtin.gepRaw.
static ManagedValue emitBuiltinGepRaw(SILGenFunction &SGF,
SILLocation loc,
SubstitutionMap substitutions,
ArrayRef<ManagedValue> args,
SGFContext C) {
assert(args.size() == 2 && "gepRaw should be given two arguments");
SILValue offsetPtr = SGF.B.createIndexRawPointer(loc,
args[0].getUnmanagedValue(),
args[1].getUnmanagedValue());
return ManagedValue::forObjectRValueWithoutOwnership(offsetPtr);
}
/// Specialized emitter for Builtin.gep.
static ManagedValue emitBuiltinGep(SILGenFunction &SGF,
SILLocation loc,
SubstitutionMap substitutions,
ArrayRef<ManagedValue> args,
SGFContext C) {
assert(substitutions.getReplacementTypes().size() == 1 &&
"gep should have two substitutions");
assert(args.size() == 3 && "gep should be given three arguments");
SILType ElemTy = SGF.getLoweredType(substitutions.getReplacementTypes()[0]);
SILType RawPtrType = args[0].getUnmanagedValue()->getType();
SILValue addr = SGF.B.createPointerToAddress(loc,
args[0].getUnmanagedValue(),
ElemTy.getAddressType(),
/*strict*/ true,
/*invariant*/ false);
addr = SGF.B.createIndexAddr(loc, addr, args[1].getUnmanagedValue(),
/*needsStackProtection=*/ true);
addr = SGF.B.createAddressToPointer(loc, addr, RawPtrType,
/*needsStackProtection=*/ true);
return ManagedValue::forObjectRValueWithoutOwnership(addr);
}
/// Specialized emitter for Builtin.getTailAddr.
static ManagedValue emitBuiltinGetTailAddr(SILGenFunction &SGF,
SILLocation loc,
SubstitutionMap substitutions,
ArrayRef<ManagedValue> args,
SGFContext C) {
assert(substitutions.getReplacementTypes().size() == 2 &&
"getTailAddr should have two substitutions");
assert(args.size() == 4 && "gep should be given four arguments");
SILType ElemTy = SGF.getLoweredType(substitutions.getReplacementTypes()[0]);
SILType TailTy = SGF.getLoweredType(substitutions.getReplacementTypes()[1]);
SILType RawPtrType = args[0].getUnmanagedValue()->getType();
SILValue addr = SGF.B.createPointerToAddress(loc,
args[0].getUnmanagedValue(),
ElemTy.getAddressType(),
/*strict*/ true,
/*invariant*/ false);
addr = SGF.B.createTailAddr(loc, addr, args[1].getUnmanagedValue(),
TailTy.getAddressType());
addr = SGF.B.createAddressToPointer(loc, addr, RawPtrType,
/*needsStackProtection=*/ false);
return ManagedValue::forObjectRValueWithoutOwnership(addr);
}
/// Specialized emitter for Builtin.beginUnpairedModifyAccess.
static ManagedValue emitBuiltinBeginUnpairedModifyAccess(SILGenFunction &SGF,
SILLocation loc,
SubstitutionMap substitutions,
ArrayRef<ManagedValue> args,
SGFContext C) {
assert(substitutions.getReplacementTypes().size() == 1 &&
"Builtin.beginUnpairedModifyAccess should have one substitution");
assert(args.size() == 3 &&
"beginUnpairedModifyAccess should be given three arguments");
SILType elemTy = SGF.getLoweredType(substitutions.getReplacementTypes()[0]);
SILValue addr = SGF.B.createPointerToAddress(loc,
args[0].getUnmanagedValue(),
elemTy.getAddressType(),
/*strict*/ true,
/*invariant*/ false);
SILType valueBufferTy =
SGF.getLoweredType(SGF.getASTContext().TheUnsafeValueBufferType);
SILValue buffer =
SGF.B.createPointerToAddress(loc, args[1].getUnmanagedValue(),
valueBufferTy.getAddressType(),
/*strict*/ true,
/*invariant*/ false);
SGF.B.createBeginUnpairedAccess(loc, addr, buffer, SILAccessKind::Modify,
SILAccessEnforcement::Dynamic,
/*noNestedConflict*/ false,
/*fromBuiltin*/ true);
return ManagedValue::forObjectRValueWithoutOwnership(SGF.emitEmptyTuple(loc));
}
/// Specialized emitter for Builtin.performInstantaneousReadAccess
static ManagedValue emitBuiltinPerformInstantaneousReadAccess(
SILGenFunction &SGF, SILLocation loc, SubstitutionMap substitutions,
ArrayRef<ManagedValue> args, SGFContext C) {
assert(substitutions.getReplacementTypes().size() == 1 &&
"Builtin.performInstantaneousReadAccess should have one substitution");
assert(args.size() == 2 &&
"Builtin.performInstantaneousReadAccess should be given "
"two arguments");
SILType elemTy = SGF.getLoweredType(substitutions.getReplacementTypes()[0]);
SILValue addr = SGF.B.createPointerToAddress(loc,
args[0].getUnmanagedValue(),
elemTy.getAddressType(),
/*strict*/ true,
/*invariant*/ false);
SILType valueBufferTy =
SGF.getLoweredType(SGF.getASTContext().TheUnsafeValueBufferType);
SILValue unusedBuffer = SGF.emitTemporaryAllocation(loc, valueBufferTy);
// Begin an "unscoped" read access. No nested conflict is possible because
// the compiler should generate the actual read for the KeyPath expression
// immediately after the call to this builtin, which forms the address of
// that real access. When noNestedConflict=true, no EndUnpairedAccess should
// be emitted.
//
// Unpaired access is necessary because a BeginAccess/EndAccess pair with no
// use will be trivially optimized away.
SGF.B.createBeginUnpairedAccess(loc, addr, unusedBuffer, SILAccessKind::Read,
SILAccessEnforcement::Dynamic,
/*noNestedConflict*/ true,
/*fromBuiltin*/ true);
return ManagedValue::forObjectRValueWithoutOwnership(SGF.emitEmptyTuple(loc));
}
/// Specialized emitter for Builtin.endUnpairedAccessModifyAccess.
static ManagedValue emitBuiltinEndUnpairedAccess(SILGenFunction &SGF,
SILLocation loc,
SubstitutionMap substitutions,
ArrayRef<ManagedValue> args,
SGFContext C) {
assert(substitutions.empty() &&
"Builtin.endUnpairedAccess should have no substitutions");
assert(args.size() == 1 &&
"endUnpairedAccess should be given one argument");
SILType valueBufferTy =
SGF.getLoweredType(SGF.getASTContext().TheUnsafeValueBufferType);
SILValue buffer = SGF.B.createPointerToAddress(loc,
args[0].getUnmanagedValue(),
valueBufferTy.getAddressType(),
/*strict*/ true,
/*invariant*/ false);
SGF.B.createEndUnpairedAccess(loc, buffer, SILAccessEnforcement::Dynamic,
/*aborted*/ false,
/*fromBuiltin*/ true);
return ManagedValue::forObjectRValueWithoutOwnership(SGF.emitEmptyTuple(loc));
}
/// Specialized emitter for the legacy Builtin.condfail.
static ManagedValue emitBuiltinLegacyCondFail(SILGenFunction &SGF,
SILLocation loc,
SubstitutionMap substitutions,
ArrayRef<ManagedValue> args,
SGFContext C) {
assert(args.size() == 1 && "condfail should be given one argument");
SGF.B.createCondFail(loc, args[0].getUnmanagedValue(),
"unknown runtime failure");
return ManagedValue::forObjectRValueWithoutOwnership(SGF.emitEmptyTuple(loc));
}
/// Specialized emitter for Builtin.castReference.
static ManagedValue
emitBuiltinCastReference(SILGenFunction &SGF,
SILLocation loc,
SubstitutionMap substitutions,
ArrayRef<ManagedValue> args,
SGFContext C) {
assert(args.size() == 1 && "castReference should be given one argument");
assert(substitutions.getReplacementTypes().size() == 2 &&
"castReference should have two subs");
auto fromTy = substitutions.getReplacementTypes()[0];
auto toTy = substitutions.getReplacementTypes()[1];
auto &fromTL = SGF.getTypeLowering(fromTy);
auto &toTL = SGF.getTypeLowering(toTy);
assert(!fromTL.isTrivial() && !toTL.isTrivial() && "expected ref type");
auto arg = args[0];
// TODO: Fix this API.
if (!fromTL.isAddress() || !toTL.isAddress()) {
if (SILType::canRefCast(arg.getType(), toTL.getLoweredType(), SGF.SGM.M)) {
// Create a reference cast, forwarding the cleanup.
// The cast takes the source reference.
return SGF.B.createUncheckedRefCast(loc, arg, toTL.getLoweredType());
}
}
// We are either casting between address-only types, or cannot promote to a
// cast of reference values.
//
// If the from/to types are invalid, then use a cast that will fail at
// runtime. We cannot catch these errors with SIL verification because they
// may legitimately occur during code specialization on dynamically
// unreachable paths.
//
// TODO: For now, we leave invalid casts in address form so that the runtime
// will trap. We could emit a noreturn call here instead which would provide
// more information to the optimizer.
SILValue srcVal = arg.ensurePlusOne(SGF, loc).forward(SGF);
SILValue fromAddr;
if (!fromTL.isAddress()) {
// Move the loadable value into a "source temp". Since the source and
// dest are RC identical, store the reference into the source temp without
// a retain. The cast will load the reference from the source temp and
// store it into a dest temp effectively forwarding the cleanup.
fromAddr = SGF.emitTemporaryAllocation(loc, srcVal->getType());
fromTL.emitStore(SGF.B, loc, srcVal, fromAddr,
StoreOwnershipQualifier::Init);
} else {
// The cast loads directly from the source address.
fromAddr = srcVal;
}
// Create a "dest temp" to hold the reference after casting it.
SILValue toAddr = SGF.emitTemporaryAllocation(loc, toTL.getLoweredType());
SGF.B.createUncheckedRefCastAddr(loc, fromAddr, fromTy->getCanonicalType(),
toAddr, toTy->getCanonicalType());
// Forward it along and register a cleanup.
if (toTL.isAddress())
return SGF.emitManagedBufferWithCleanup(toAddr);
// Load the destination value.
auto result = toTL.emitLoad(SGF.B, loc, toAddr, LoadOwnershipQualifier::Take);
return SGF.emitManagedRValueWithCleanup(result);
}
/// Specialized emitter for Builtin.reinterpretCast.
static ManagedValue emitBuiltinReinterpretCast(SILGenFunction &SGF,
SILLocation loc,
SubstitutionMap substitutions,
ArrayRef<ManagedValue> args,
SGFContext C) {
assert(args.size() == 1 && "reinterpretCast should be given one argument");
assert(substitutions.getReplacementTypes().size() == 2 &&
"reinterpretCast should have two subs");
auto &fromTL = SGF.getTypeLowering(substitutions.getReplacementTypes()[0]);
auto &toTL = SGF.getTypeLowering(substitutions.getReplacementTypes()[1]);
// If casting between address types, cast the address.
if (fromTL.isAddress() || toTL.isAddress()) {
SILValue fromAddr;
// If the from value is not an address, move it to a buffer.
if (!fromTL.isAddress()) {
fromAddr = SGF.emitTemporaryAllocation(loc, args[0].getValue()->getType());
fromTL.emitStore(SGF.B, loc, args[0].getValue(), fromAddr,
StoreOwnershipQualifier::Init);
} else {
fromAddr = args[0].getValue();
}
auto toAddr = SGF.B.createUncheckedAddrCast(loc, fromAddr,
toTL.getLoweredType().getAddressType());
// Load and retain the destination value if it's loadable. Leave the cleanup
// on the original value since we don't know anything about it's type.
if (!toTL.isAddress()) {
return SGF.emitManagedLoadCopy(loc, toAddr, toTL);
}
// Leave the cleanup on the original value.
if (toTL.isTrivial())
return ManagedValue::forTrivialAddressRValue(toAddr);
// Initialize the +1 result buffer without taking the incoming value. The
// source and destination cleanups will be independent.
return SGF.B.bufferForExpr(
loc, toTL.getLoweredType(), toTL, C,
[&](SILValue bufferAddr) {
SGF.B.createCopyAddr(loc, toAddr, bufferAddr, IsNotTake,
IsInitialization);
});
}
// Create the appropriate bitcast based on the source and dest types.
ManagedValue in = args[0];
SILType resultTy = toTL.getLoweredType();
return SGF.B.createUncheckedBitCast(loc, in, resultTy);
}
/// Specialized emitter for Builtin.castToBridgeObject.
static ManagedValue emitBuiltinCastToBridgeObject(SILGenFunction &SGF,
SILLocation loc,
SubstitutionMap subs,
ArrayRef<ManagedValue> args,
SGFContext C) {
assert(args.size() == 2 && "cast should have two arguments");
assert(subs.getReplacementTypes().size() == 1 &&
"cast should have a type substitution");
// Take the reference type argument and cast it to BridgeObject.
SILType objPointerType = SILType::getBridgeObjectType(SGF.F.getASTContext());
// Bail if the source type is not a class reference of some kind.
auto sourceType = subs.getReplacementTypes()[0];
if (!sourceType->mayHaveSuperclass() &&
!sourceType->isClassExistentialType()) {
SGF.SGM.diagnose(loc, diag::invalid_sil_builtin,
"castToBridgeObject source must be a class");
return SGF.emitUndef(objPointerType);
}
ManagedValue ref = args[0];
SILValue bits = args[1].getUnmanagedValue();
// If the argument is existential, open it.
if (sourceType->isClassExistentialType()) {
auto openedTy = ExistentialArchetypeType::get(sourceType->getCanonicalType());
SILType loweredOpenedTy = SGF.getLoweredLoadableType(openedTy);
ref = SGF.B.createOpenExistentialRef(loc, ref, loweredOpenedTy);
}
return SGF.B.createRefToBridgeObject(loc, ref, bits);
}
/// Specialized emitter for Builtin.castReferenceFromBridgeObject.
static ManagedValue emitBuiltinCastReferenceFromBridgeObject(
SILGenFunction &SGF,
SILLocation loc,
SubstitutionMap subs,
ArrayRef<ManagedValue> args,
SGFContext C) {
assert(args.size() == 1 && "cast should have one argument");
assert(subs.getReplacementTypes().size() == 1 &&
"cast should have a type substitution");
// The substitution determines the destination type.
auto destTy = subs.getReplacementTypes()[0];
SILType destType = SGF.getLoweredType(destTy);
// Bail if the source type is not a class reference of some kind.
if (!destTy->isBridgeableObjectType() || !destType.isObject()) {
SGF.SGM.diagnose(loc, diag::invalid_sil_builtin,
"castReferenceFromBridgeObject dest must be an object type");
// Recover by propagating an undef result.
return SGF.emitUndef(destType);
}
return SGF.B.createBridgeObjectToRef(loc, args[0], destType);
}
static ManagedValue emitBuiltinCastBitPatternFromBridgeObject(
SILGenFunction &SGF,
SILLocation loc,
SubstitutionMap subs,
ArrayRef<ManagedValue> args,
SGFContext C) {
assert(args.size() == 1 && "cast should have one argument");
assert(subs.empty() && "cast should not have subs");
SILType wordType = SILType::getBuiltinWordType(SGF.getASTContext());
SILValue result = SGF.B.createBridgeObjectToWord(loc, args[0].getValue(),
wordType);
return ManagedValue::forObjectRValueWithoutOwnership(result);
}
static ManagedValue emitBuiltinClassifyBridgeObject(SILGenFunction &SGF,
SILLocation loc,
SubstitutionMap subs,
ArrayRef<ManagedValue> args,
SGFContext C) {
assert(args.size() == 1 && "classify should have one argument");
assert(subs.empty() && "classify should not have subs");
SILValue result = SGF.B.createClassifyBridgeObject(loc, args[0].getValue());
return ManagedValue::forObjectRValueWithoutOwnership(result);
}
static ManagedValue emitBuiltinValueToBridgeObject(SILGenFunction &SGF,
SILLocation loc,
SubstitutionMap subs,
ArrayRef<ManagedValue> args,
SGFContext C) {
assert(args.size() == 1 && "ValueToBridgeObject should have one argument");
assert(subs.getReplacementTypes().size() == 1 &&
"ValueToBridgeObject should have one sub");
Type argTy = subs.getReplacementTypes()[0];
if (!argTy->is<BuiltinIntegerType>()) {
SGF.SGM.diagnose(loc, diag::invalid_sil_builtin,
"argument to builtin should be a builtin integer");
SILType objPointerType = SILType::getBridgeObjectType(SGF.F.getASTContext());
return SGF.emitUndef(objPointerType);
}
SILValue result = SGF.B.createValueToBridgeObject(loc, args[0].getValue());
return SGF.emitManagedCopy(loc, result);
}
// This should only accept as an operand type single-refcounted-pointer types,
// class existentials, or single-payload enums (optional). Type checking must be
// deferred until IRGen so Builtin.isUnique can be called from a transparent
// generic wrapper (we can only type check after specialization).
static ManagedValue emitBuiltinIsUnique(SILGenFunction &SGF,
SILLocation loc,
SubstitutionMap subs,
ArrayRef<ManagedValue> args,
SGFContext C) {
assert(subs.getReplacementTypes().size() == 1 &&
"isUnique should have a single substitution");
assert(args.size() == 1 && "isUnique should have a single argument");
assert((args[0].getType().isAddress() && !args[0].hasCleanup()) &&
"Builtin.isUnique takes an address.");
return ManagedValue::forObjectRValueWithoutOwnership(
SGF.B.createIsUnique(loc, args[0].getValue()));
}
// This force-casts the incoming address to NativeObject assuming the caller has
// performed all necessary checks. For example, this may directly cast a
// single-payload enum to a NativeObject reference.
static ManagedValue
emitBuiltinIsUnique_native(SILGenFunction &SGF,
SILLocation loc,
SubstitutionMap subs,
ArrayRef<ManagedValue> args,
SGFContext C) {
assert(subs.getReplacementTypes().size() == 1 &&
"isUnique_native should have one sub.");
assert(args.size() == 1 && "isUnique_native should have one arg.");
auto ToType =
SILType::getNativeObjectType(SGF.getASTContext()).getAddressType();
auto toAddr = SGF.B.createUncheckedAddrCast(loc, args[0].getValue(), ToType);
SILValue result = SGF.B.createIsUnique(loc, toAddr);
return ManagedValue::forObjectRValueWithoutOwnership(result);
}
static ManagedValue
emitBuiltinBeginCOWMutation(SILGenFunction &SGF,