-
Notifications
You must be signed in to change notification settings - Fork 10.5k
/
Copy pathSILBridging.cpp
959 lines (798 loc) · 35.2 KB
/
SILBridging.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
//===--- SILBridgingUtils.cpp - Utilities for swift bridging --------------===//
//
// 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 "swift/Basic/BridgingUtils.h"
#include "swift/SIL/SILNode.h"
#include "swift/SIL/ApplySite.h"
#include "swift/SIL/SILBridgingUtils.h"
#include "swift/SIL/SILGlobalVariable.h"
#include "swift/SIL/SILBuilder.h"
#include <string>
using namespace swift;
namespace {
bool nodeMetatypesInitialized = false;
// Filled in by class registration in initializeSwiftModules().
SwiftMetatype nodeMetatypes[(unsigned)SILNodeKind::Last_SILNode + 1];
}
// Does return null if initializeSwiftModules() is never called.
SwiftMetatype SILNode::getSILNodeMetatype(SILNodeKind kind) {
SwiftMetatype metatype = nodeMetatypes[(unsigned)kind];
assert((!nodeMetatypesInitialized || metatype) &&
"no metatype for bridged SIL node");
return metatype;
}
static_assert(sizeof(BridgedLocation) == sizeof(SILDebugLocation),
"BridgedLocation has wrong size");
/// Fills \p storage with all Values from the bridged \p values array.
ArrayRef<SILValue> swift::getSILValues(BridgedValueArray values,
SmallVectorImpl<SILValue> &storage) {
auto *base = reinterpret_cast<const SwiftObject *>(values.data);
// The bridged array contains class existentials, which have a layout of two
// words. The first word is the actual object. Pick the objects and store them
// into storage.
for (unsigned idx = 0; idx < values.count; ++idx) {
storage.push_back(castToSILValue({base[idx * 2]}));
}
return storage;
}
//===----------------------------------------------------------------------===//
// Class registration
//===----------------------------------------------------------------------===//
static llvm::StringMap<SILNodeKind> valueNamesToKind;
static llvm::SmallPtrSet<SwiftMetatype, 4> unimplementedTypes;
// Utility to fill in a metatype of an "unimplemented" class for a whole range
// of class types.
static void setUnimplementedRange(SwiftMetatype metatype,
SILNodeKind from, SILNodeKind to) {
unimplementedTypes.insert(metatype);
for (unsigned kind = (unsigned)from; kind <= (unsigned)to; ++kind) {
assert((!nodeMetatypes[kind] || unimplementedTypes.count(metatype)) &&
"unimplemented nodes must be registered first");
nodeMetatypes[kind] = metatype;
}
}
/// Registers the metatype of a swift SIL class.
/// Called by initializeSwiftModules().
void registerBridgedClass(StringRef className, SwiftMetatype metatype) {
nodeMetatypesInitialized = true;
// Handle the important non Node classes.
if (className == "BasicBlock")
return SILBasicBlock::registerBridgedMetatype(metatype);
if (className == "GlobalVariable")
return SILGlobalVariable::registerBridgedMetatype(metatype);
if (className == "BlockArgument") {
nodeMetatypes[(unsigned)SILNodeKind::SILPhiArgument] = metatype;
return;
}
if (className == "FunctionArgument") {
nodeMetatypes[(unsigned)SILNodeKind::SILFunctionArgument] = metatype;
return;
}
// Pre-populate the "unimplemented" ranges of metatypes.
// If a specific class is not implemented in Swift yet, it bridges to an
// "unimplemented" class. This ensures that optimizations handle _all_ kind of
// instructions gracefully, without the need to define the not-yet-used
// classes in Swift.
#define VALUE_RANGE(ID) SILNodeKind::First_##ID, SILNodeKind::Last_##ID
if (className == "UnimplementedRefCountingInst")
return setUnimplementedRange(metatype, VALUE_RANGE(RefCountingInst));
if (className == "UnimplementedSingleValueInst")
return setUnimplementedRange(metatype, VALUE_RANGE(SingleValueInstruction));
if (className == "UnimplementedInstruction")
return setUnimplementedRange(metatype, VALUE_RANGE(SILInstruction));
#undef VALUE_RANGE
if (valueNamesToKind.empty()) {
#define VALUE(ID, PARENT) \
valueNamesToKind[#ID] = SILNodeKind::ID;
#define BRIDGED_NON_VALUE_INST(ID, NAME, PARENT, MEMBEHAVIOR, MAYRELEASE) \
VALUE(ID, NAME)
#define ARGUMENT(ID, PARENT) \
VALUE(ID, NAME)
#define BRIDGED_SINGLE_VALUE_INST(ID, NAME, PARENT, MEMBEHAVIOR, MAYRELEASE) \
VALUE(ID, NAME)
#define MULTIPLE_VALUE_INST(ID, NAME, PARENT, MEMBEHAVIOR, MAYRELEASE) \
VALUE(ID, NAME)
#include "swift/SIL/SILNodes.def"
}
std::string prefixedName;
auto iter = valueNamesToKind.find(className);
if (iter == valueNamesToKind.end()) {
// Try again with a "SIL" prefix. For example Argument -> SILArgument.
prefixedName = std::string("SIL") + std::string(className);
iter = valueNamesToKind.find(prefixedName);
if (iter == valueNamesToKind.end()) {
llvm::errs() << "Unknown bridged node class " << className << '\n';
abort();
}
className = prefixedName;
}
SILNodeKind kind = iter->second;
SwiftMetatype existingTy = nodeMetatypes[(unsigned)kind];
if (existingTy && !unimplementedTypes.count(existingTy)) {
llvm::errs() << "Double registration of class " << className << '\n';
abort();
}
nodeMetatypes[(unsigned)kind] = metatype;
}
//===----------------------------------------------------------------------===//
// SILFunction
//===----------------------------------------------------------------------===//
llvm::StringRef SILFunction_getName(BridgedFunction function) {
return castToFunction(function)->getName();
}
std::string SILFunction_debugDescription(BridgedFunction function) {
std::string str;
llvm::raw_string_ostream os(str);
castToFunction(function)->print(os);
str.pop_back(); // Remove trailing newline.
return str;
}
SwiftInt SILFunction_hasOwnership(BridgedFunction function) {
return castToFunction(function)->hasOwnership() ? 1 : 0;
}
OptionalBridgedBasicBlock SILFunction_firstBlock(BridgedFunction function) {
SILFunction *f = castToFunction(function);
if (f->empty())
return {nullptr};
return {f->getEntryBlock()};
}
OptionalBridgedBasicBlock SILFunction_lastBlock(BridgedFunction function) {
SILFunction *f = castToFunction(function);
if (f->empty())
return {nullptr};
return {&*f->rbegin()};
}
SwiftInt SILFunction_numIndirectResultArguments(BridgedFunction function) {
return castToFunction(function)->getLoweredFunctionType()->
getNumIndirectFormalResults();
}
SwiftInt SILFunction_getSelfArgumentIndex(BridgedFunction function) {
CanSILFunctionType fTy = castToFunction(function)->getLoweredFunctionType();
if (!fTy->hasSelfParam())
return -1;
return fTy->getNumParameters() + fTy->getNumIndirectFormalResults() - 1;
}
SwiftInt SILFunction_getNumSILArguments(BridgedFunction function) {
SILFunction *f = castToFunction(function);
SILFunctionConventions conv(f->getConventionsInContext());
return conv.getNumSILArguments();
}
BridgedType SILFunction_getSILArgumentType(BridgedFunction function, SwiftInt idx) {
SILFunction *f = castToFunction(function);
SILFunctionConventions conv(f->getConventionsInContext());
SILType argTy = conv.getSILArgumentType(idx, f->getTypeExpansionContext());
return {argTy.getOpaqueValue()};
}
BridgedType SILFunction_getSILResultType(BridgedFunction function) {
SILFunction *f = castToFunction(function);
SILFunctionConventions conv(f->getConventionsInContext());
SILType resTy = conv.getSILResultType(f->getTypeExpansionContext());
return {resTy.getOpaqueValue()};
}
SwiftInt SILFunction_isSwift51RuntimeAvailable(BridgedFunction function) {
SILFunction *f = castToFunction(function);
if (f->getResilienceExpansion() != ResilienceExpansion::Maximal)
return 0;
ASTContext &ctxt = f->getModule().getASTContext();
return AvailabilityContext::forDeploymentTarget(ctxt).isContainedIn(
ctxt.getSwift51Availability());
}
SwiftInt SILFunction_hasSemanticsAttr(BridgedFunction function,
StringRef attrName) {
SILFunction *f = castToFunction(function);
return f->hasSemanticsAttr(attrName) ? 1 : 0;
}
//===----------------------------------------------------------------------===//
// SILBasicBlock
//===----------------------------------------------------------------------===//
static_assert(BridgedSuccessorSize == sizeof(SILSuccessor),
"wrong bridged SILSuccessor size");
OptionalBridgedBasicBlock SILBasicBlock_next(BridgedBasicBlock block) {
SILBasicBlock *b = castToBasicBlock(block);
auto iter = std::next(b->getIterator());
if (iter == b->getParent()->end())
return {nullptr};
return {&*iter};
}
OptionalBridgedBasicBlock SILBasicBlock_previous(BridgedBasicBlock block) {
SILBasicBlock *b = castToBasicBlock(block);
auto iter = std::next(b->getReverseIterator());
if (iter == b->getParent()->rend())
return {nullptr};
return {&*iter};
}
BridgedFunction SILBasicBlock_getFunction(BridgedBasicBlock block) {
return {castToBasicBlock(block)->getParent()};
}
std::string SILBasicBlock_debugDescription(BridgedBasicBlock block) {
std::string str;
llvm::raw_string_ostream os(str);
castToBasicBlock(block)->print(os);
str.pop_back(); // Remove trailing newline.
return str;
}
OptionalBridgedInstruction SILBasicBlock_firstInst(BridgedBasicBlock block) {
SILBasicBlock *b = castToBasicBlock(block);
if (b->empty())
return {nullptr};
return {b->front().asSILNode()};
}
OptionalBridgedInstruction SILBasicBlock_lastInst(BridgedBasicBlock block) {
SILBasicBlock *b = castToBasicBlock(block);
if (b->empty())
return {nullptr};
return {b->back().asSILNode()};
}
SwiftInt SILBasicBlock_getNumArguments(BridgedBasicBlock block) {
return castToBasicBlock(block)->getNumArguments();
}
BridgedArgument SILBasicBlock_getArgument(BridgedBasicBlock block, SwiftInt index) {
return {castToBasicBlock(block)->getArgument(index)};
}
BridgedArgument SILBasicBlock_addBlockArgument(BridgedBasicBlock block,
BridgedType type,
BridgedOwnership ownership) {
return {castToBasicBlock(block)->createPhiArgument(castToSILType(type),
castToOwnership(ownership))};
}
void SILBasicBlock_eraseArgument(BridgedBasicBlock block, SwiftInt index) {
castToBasicBlock(block)->eraseArgument(index);
}
OptionalBridgedSuccessor SILBasicBlock_getFirstPred(BridgedBasicBlock block) {
return {castToBasicBlock(block)->pred_begin().getSuccessorRef()};
}
static SILSuccessor *castToSuccessor(BridgedSuccessor succ) {
return const_cast<SILSuccessor *>(static_cast<const SILSuccessor *>(succ.succ));
}
OptionalBridgedSuccessor SILSuccessor_getNext(BridgedSuccessor succ) {
return {castToSuccessor(succ)->getNext()};
}
BridgedBasicBlock SILSuccessor_getTargetBlock(BridgedSuccessor succ) {
return {castToSuccessor(succ)->getBB()};
}
BridgedInstruction SILSuccessor_getContainingInst(BridgedSuccessor succ) {
return {castToSuccessor(succ)->getContainingInst()};
}
//===----------------------------------------------------------------------===//
// SILArgument
//===----------------------------------------------------------------------===//
BridgedBasicBlock SILArgument_getParent(BridgedArgument argument) {
return {castToArgument(argument)->getParent()};
}
SwiftInt SILArgument_isExclusiveIndirectParameter(BridgedArgument argument) {
auto *arg = castToArgument<SILFunctionArgument>(argument);
return arg->getArgumentConvention().isExclusiveIndirectParameter();
}
//===----------------------------------------------------------------------===//
// SILValue
//===----------------------------------------------------------------------===//
static_assert(BridgedOperandSize == sizeof(Operand),
"wrong bridged Operand size");
std::string SILNode_debugDescription(BridgedNode node) {
std::string str;
llvm::raw_string_ostream os(str);
castToSILNode(node)->print(os);
str.pop_back(); // Remove trailing newline.
return str;
}
static Operand *castToOperand(BridgedOperand operand) {
return const_cast<Operand *>(static_cast<const Operand *>(operand.op));
}
BridgedValue Operand_getValue(BridgedOperand operand) {
return {castToOperand(operand)->get()};
}
OptionalBridgedOperand Operand_nextUse(BridgedOperand operand) {
return {castToOperand(operand)->getNextUse()};
}
BridgedInstruction Operand_getUser(BridgedOperand operand) {
return {castToOperand(operand)->getUser()->asSILNode()};
}
SwiftInt Operand_isTypeDependent(BridgedOperand operand) {
return castToOperand(operand)->isTypeDependent() ? 1 : 0;
}
OptionalBridgedOperand SILValue_firstUse(BridgedValue value) {
return {*castToSILValue(value)->use_begin()};
}
BridgedType SILValue_getType(BridgedValue value) {
return { castToSILValue(value)->getType().getOpaqueValue() };
}
BridgedOwnership SILValue_getOwnership(BridgedValue value) {
switch (castToSILValue(value)->getOwnershipKind()) {
case OwnershipKind::Any:
llvm_unreachable("Invalid ownership for value");
case OwnershipKind::Unowned: return Ownership_Unowned;
case OwnershipKind::Owned: return Ownership_Owned;
case OwnershipKind::Guaranteed: return Ownership_Guaranteed;
case OwnershipKind::None: return Ownership_None;
}
}
//===----------------------------------------------------------------------===//
// SILType
//===----------------------------------------------------------------------===//
std::string SILType_debugDescription(BridgedType type) {
std::string str;
llvm::raw_string_ostream os(str);
castToSILType(type).print(os);
str.pop_back(); // Remove trailing newline.
return str;
}
SwiftInt SILType_isAddress(BridgedType type) {
return castToSILType(type).isAddress();
}
SwiftInt SILType_isTrivial(BridgedType type, BridgedFunction function) {
return castToSILType(type).isTrivial(*castToFunction(function));
}
SwiftInt SILType_isReferenceCounted(BridgedType type, BridgedFunction function) {
SILFunction *f = castToFunction(function);
return castToSILType(type).isReferenceCounted(f->getModule()) ? 1 : 0;
}
SwiftInt SILType_isNonTrivialOrContainsRawPointer(BridgedType type,
BridgedFunction function) {
SILFunction *f = castToFunction(function);
return castToSILType(type).isNonTrivialOrContainsRawPointer(*f);
}
SwiftInt SILType_isNominal(BridgedType type) {
return castToSILType(type).getNominalOrBoundGenericNominal() ? 1 : 0;
}
SwiftInt SILType_isClass(BridgedType type) {
return castToSILType(type).getClassOrBoundGenericClass() ? 1 : 0;
}
SwiftInt SILType_isStruct(BridgedType type) {
return castToSILType(type).getStructOrBoundGenericStruct() ? 1 : 0;
}
SwiftInt SILType_isTuple(BridgedType type) {
return castToSILType(type).is<TupleType>() ? 1 : 0;
}
SwiftInt SILType_isEnum(BridgedType type) {
return castToSILType(type).getEnumOrBoundGenericEnum() ? 1 : 0;
}
SwiftInt SILType_getNumTupleElements(BridgedType type) {
TupleType *tupleTy = castToSILType(type).castTo<TupleType>();
return tupleTy->getNumElements();
}
BridgedType SILType_getTupleElementType(BridgedType type, SwiftInt elementIdx) {
SILType ty = castToSILType(type);
SILType elmtTy = ty.getTupleElementType((unsigned)elementIdx);
return {elmtTy.getOpaqueValue()};
}
SwiftInt SILType_getNumNominalFields(BridgedType type) {
SILType silType = castToSILType(type);
auto *nominal = silType.getNominalOrBoundGenericNominal();
assert(nominal && "expected nominal type");
return getNumFieldsInNominal(nominal);
}
BridgedType SILType_getNominalFieldType(BridgedType type, SwiftInt index,
BridgedFunction function) {
SILType silType = castToSILType(type);
SILFunction *silFunction = castToFunction(function);
NominalTypeDecl *decl = silType.getNominalOrBoundGenericNominal();
VarDecl *field = getIndexedField(decl, (unsigned)index);
SILType fieldType = silType.getFieldType(
field, silFunction->getModule(), silFunction->getTypeExpansionContext());
return {fieldType.getOpaqueValue()};
}
SwiftInt SILType_getFieldIdxOfNominalType(BridgedType type,
StringRef fieldName) {
SILType ty = castToSILType(type);
auto *nominal = ty.getNominalOrBoundGenericNominal();
if (!nominal)
return -1;
SmallVector<NominalTypeDecl *, 5> decls;
decls.push_back(nominal);
if (auto *cd = dyn_cast<ClassDecl>(nominal)) {
while ((cd = cd->getSuperclassDecl()) != nullptr) {
decls.push_back(cd);
}
}
std::reverse(decls.begin(), decls.end());
SwiftInt idx = 0;
for (auto *decl : decls) {
for (VarDecl *field : decl->getStoredProperties()) {
if (field->getName().str() == fieldName)
return idx;
idx++;
}
}
return -1;
}
SwiftInt SILType_getCaseIdxOfEnumType(BridgedType type,
StringRef caseName) {
SILType ty = castToSILType(type);
auto *enumDecl = ty.getEnumOrBoundGenericEnum();
if (!enumDecl)
return -1;
SwiftInt idx = 0;
for (EnumElementDecl *elem : enumDecl->getAllElements()) {
if (elem->getNameStr() == caseName)
return idx;
idx++;
}
return -1;
}
//===----------------------------------------------------------------------===//
// SubstitutionMap
//===----------------------------------------------------------------------===//
BridgedSubstitutionMap SubstitutionMap_getEmpty() {
return {SubstitutionMap().getOpaqueValue()};
}
//===----------------------------------------------------------------------===//
// SILGlobalVariable
//===----------------------------------------------------------------------===//
llvm::StringRef SILGlobalVariable_getName(BridgedGlobalVar global) {
return castToGlobal(global)->getName();
}
std::string SILGlobalVariable_debugDescription(BridgedGlobalVar global) {
std::string str;
llvm::raw_string_ostream os(str);
castToGlobal(global)->print(os);
str.pop_back(); // Remove trailing newline.
return str;
}
SwiftInt SILGlobalVariable_isLet(BridgedGlobalVar global) {
return castToGlobal(global)->isLet();
}
//===----------------------------------------------------------------------===//
// SILInstruction
//===----------------------------------------------------------------------===//
OptionalBridgedInstruction SILInstruction_next(BridgedInstruction inst) {
SILInstruction *i = castToInst(inst);
auto iter = std::next(i->getIterator());
if (iter == i->getParent()->end())
return {nullptr};
return {iter->asSILNode()};
}
OptionalBridgedInstruction SILInstruction_previous(BridgedInstruction inst) {
SILInstruction *i = castToInst(inst);
auto iter = std::next(i->getReverseIterator());
if (iter == i->getParent()->rend())
return {nullptr};
return {iter->asSILNode()};
}
BridgedBasicBlock SILInstruction_getParent(BridgedInstruction inst) {
SILInstruction *i = castToInst(inst);
assert(!i->isStaticInitializerInst() &&
"cannot get the parent of a static initializer instruction");
return {i->getParent()};
}
BridgedArrayRef SILInstruction_getOperands(BridgedInstruction inst) {
auto operands = castToInst(inst)->getAllOperands();
return {(const unsigned char *)operands.data(), operands.size()};
}
void SILInstruction_setOperand(BridgedInstruction inst, SwiftInt index,
BridgedValue value) {
castToInst(inst)->setOperand((unsigned)index, castToSILValue(value));
}
BridgedLocation SILInstruction_getLocation(BridgedInstruction inst) {
SILDebugLocation loc = castToInst(inst)->getDebugLocation();
return *reinterpret_cast<BridgedLocation *>(&loc);
}
BridgedMemoryBehavior SILInstruction_getMemBehavior(BridgedInstruction inst) {
return (BridgedMemoryBehavior)castToInst(inst)->getMemoryBehavior();
}
bool SILInstruction_mayRelease(BridgedInstruction inst) {
return castToInst(inst)->mayRelease();
}
BridgedInstruction MultiValueInstResult_getParent(BridgedMultiValueResult result) {
return {static_cast<MultipleValueInstructionResult *>(result.obj)->getParent()};
}
SwiftInt MultiValueInstResult_getIndex(BridgedMultiValueResult result) {
auto *rs = static_cast<MultipleValueInstructionResult *>(result.obj);
return (SwiftInt)rs->getIndex();
}
SwiftInt MultipleValueInstruction_getNumResults(BridgedInstruction inst) {
return castToInst<MultipleValueInstruction>(inst)->getNumResults();
}
BridgedMultiValueResult
MultipleValueInstruction_getResult(BridgedInstruction inst, SwiftInt index) {
return {castToInst<MultipleValueInstruction>(inst)->getResult(index)};
}
BridgedArrayRef TermInst_getSuccessors(BridgedInstruction term) {
auto successors = castToInst<TermInst>(term)->getSuccessors();
return {(const unsigned char *)successors.data(), successors.size()};
}
//===----------------------------------------------------------------------===//
// Instruction classes
//===----------------------------------------------------------------------===//
llvm::StringRef CondFailInst_getMessage(BridgedInstruction cfi) {
return castToInst<CondFailInst>(cfi)->getMessage();
}
BridgedBuiltinID BuiltinInst_getID(BridgedInstruction bi) {
return (BridgedBuiltinID)castToInst<BuiltinInst>(bi)->getBuiltinInfo().ID;
}
BridgedGlobalVar GlobalAccessInst_getGlobal(BridgedInstruction globalInst) {
return {castToInst<GlobalAccessInst>(globalInst)->getReferencedGlobal()};
}
BridgedFunction FunctionRefInst_getReferencedFunction(BridgedInstruction fri) {
return {castToInst<FunctionRefInst>(fri)->getReferencedFunction()};
}
llvm::StringRef StringLiteralInst_getValue(BridgedInstruction sli) {
return castToInst<StringLiteralInst>(sli)->getValue();
}
SwiftInt TupleExtractInst_fieldIndex(BridgedInstruction tei) {
return castToInst<TupleExtractInst>(tei)->getFieldIndex();
}
SwiftInt TupleElementAddrInst_fieldIndex(BridgedInstruction teai) {
return castToInst<TupleElementAddrInst>(teai)->getFieldIndex();
}
SwiftInt StructExtractInst_fieldIndex(BridgedInstruction sei) {
return castToInst<StructExtractInst>(sei)->getFieldIndex();
}
OptionalBridgedValue StructInst_getUniqueNonTrivialFieldValue(BridgedInstruction si) {
return {castToInst<StructInst>(si)->getUniqueNonTrivialFieldValue()};
}
SwiftInt StructElementAddrInst_fieldIndex(BridgedInstruction seai) {
return castToInst<StructElementAddrInst>(seai)->getFieldIndex();
}
SwiftInt ProjectBoxInst_fieldIndex(BridgedInstruction pbi) {
return castToInst<ProjectBoxInst>(pbi)->getFieldIndex();
}
SwiftInt EnumInst_caseIndex(BridgedInstruction ei) {
return castToInst<EnumInst>(ei)->getCaseIndex();
}
SwiftInt UncheckedEnumDataInst_caseIndex(BridgedInstruction uedi) {
return castToInst<UncheckedEnumDataInst>(uedi)->getCaseIndex();
}
SwiftInt InitEnumDataAddrInst_caseIndex(BridgedInstruction ieda) {
return castToInst<InitEnumDataAddrInst>(ieda)->getCaseIndex();
}
SwiftInt UncheckedTakeEnumDataAddrInst_caseIndex(BridgedInstruction utedi) {
return castToInst<UncheckedTakeEnumDataAddrInst>(utedi)->getCaseIndex();
}
SwiftInt InjectEnumAddrInst_caseIndex(BridgedInstruction ieai) {
return castToInst<InjectEnumAddrInst>(ieai)->getCaseIndex();
}
SwiftInt RefElementAddrInst_fieldIndex(BridgedInstruction reai) {
return castToInst<RefElementAddrInst>(reai)->getFieldIndex();
}
SwiftInt RefElementAddrInst_fieldIsLet(BridgedInstruction reai) {
return castToInst<RefElementAddrInst>(reai)->getField()->isLet();
}
SwiftInt PartialApplyInst_numArguments(BridgedInstruction pai) {
return castToInst<PartialApplyInst>(pai)->getNumArguments();
}
SwiftInt ApplyInst_numArguments(BridgedInstruction ai) {
return castToInst<ApplyInst>(ai)->getNumArguments();
}
SwiftInt PartialApply_getCalleeArgIndexOfFirstAppliedArg(BridgedInstruction pai) {
auto *paiInst = castToInst<PartialApplyInst>(pai);
return ApplySite(paiInst).getCalleeArgIndexOfFirstAppliedArg();
}
SwiftInt PartialApplyInst_isOnStack(BridgedInstruction pai) {
return castToInst<PartialApplyInst>(pai)->isOnStack() ? 1 : 0;
}
SwiftInt AllocRefInstBase_isObjc(BridgedInstruction arb) {
return castToInst<AllocRefInstBase>(arb)->isObjC();
}
SwiftInt AllocRefInstBase_canAllocOnStack(BridgedInstruction arb) {
return castToInst<AllocRefInstBase>(arb)->canAllocOnStack();
}
SwiftInt BeginApplyInst_numArguments(BridgedInstruction tai) {
return castToInst<BeginApplyInst>(tai)->getNumArguments();
}
SwiftInt TryApplyInst_numArguments(BridgedInstruction tai) {
return castToInst<TryApplyInst>(tai)->getNumArguments();
}
BridgedBasicBlock BranchInst_getTargetBlock(BridgedInstruction bi) {
return {castToInst<BranchInst>(bi)->getDestBB()};
}
SwiftInt SwitchEnumInst_getNumCases(BridgedInstruction se) {
return castToInst<SwitchEnumInst>(se)->getNumCases();
}
SwiftInt SwitchEnumInst_getCaseIndex(BridgedInstruction se, SwiftInt idx) {
auto *seInst = castToInst<SwitchEnumInst>(se);
return seInst->getModule().getCaseIndex(seInst->getCase(idx).first);
}
SwiftInt StoreInst_getStoreOwnership(BridgedInstruction store) {
return (SwiftInt)castToInst<StoreInst>(store)->getOwnershipQualifier();
}
BridgedAccessKind BeginAccessInst_getAccessKind(BridgedInstruction beginAccess) {
auto kind = castToInst<BeginAccessInst>(beginAccess)->getAccessKind();
switch (kind) {
case SILAccessKind::Init:
return BridgedAccessKind::AccessKind_Init;
case SILAccessKind::Read:
return BridgedAccessKind::AccessKind_Read;
case SILAccessKind::Modify:
return BridgedAccessKind::AccessKind_Modify;
case SILAccessKind::Deinit:
return BridgedAccessKind::AccessKind_Deinit;
}
}
SwiftInt CopyAddrInst_isTakeOfSrc(BridgedInstruction copyAddr) {
return castToInst<CopyAddrInst>(copyAddr)->isTakeOfSrc() ? 1 : 0;
}
SwiftInt CopyAddrInst_isInitializationOfDest(BridgedInstruction copyAddr) {
return castToInst<CopyAddrInst>(copyAddr)->isInitializationOfDest() ? 1 : 0;
}
void RefCountingInst_setIsAtomic(BridgedInstruction rc, bool isAtomic) {
castToInst<RefCountingInst>(rc)->setAtomicity(
isAtomic ? RefCountingInst::Atomicity::Atomic
: RefCountingInst::Atomicity::NonAtomic);
}
bool RefCountingInst_getIsAtomic(BridgedInstruction rc) {
return castToInst<RefCountingInst>(rc)->getAtomicity() ==
RefCountingInst::Atomicity::Atomic;
}
SwiftInt CondBranchInst_getNumTrueArgs(BridgedInstruction cbr) {
return castToInst<CondBranchInst>(cbr)->getNumTrueArgs();
}
BridgedSubstitutionMap ApplySite_getSubstitutionMap(BridgedInstruction inst) {
auto as = ApplySite(castToInst(inst));
return {as.getSubstitutionMap().getOpaqueValue()};
}
BridgedArgumentConvention
ApplySite_getArgumentConvention(BridgedInstruction inst, SwiftInt calleeArgIdx) {
auto as = ApplySite(castToInst(inst));
auto conv = as.getSubstCalleeConv().getSILArgumentConvention(calleeArgIdx);
switch (conv.Value) {
case SILArgumentConvention::Indirect_Inout:
return ArgumentConvention_Indirect_In;
case SILArgumentConvention::Indirect_InoutAliasable:
return ArgumentConvention_Indirect_In_Constant;
case SILArgumentConvention::Indirect_In_Guaranteed:
return ArgumentConvention_Indirect_In_Guaranteed;
case SILArgumentConvention::Indirect_In:
return ArgumentConvention_Indirect_Inout;
case SILArgumentConvention::Indirect_In_Constant:
return ArgumentConvention_Indirect_InoutAliasable;
case SILArgumentConvention::Indirect_Out:
return ArgumentConvention_Indirect_Out;
case SILArgumentConvention::Direct_Unowned:
return ArgumentConvention_Direct_Owned;
case SILArgumentConvention::Direct_Owned:
return ArgumentConvention_Direct_Unowned;
case SILArgumentConvention::Direct_Guaranteed:
return ArgumentConvention_Direct_Guaranteed;
}
}
SwiftInt ApplySite_getNumArguments(BridgedInstruction inst) {
auto as = ApplySite(castToInst(inst));
return as.getNumArguments();
}
//===----------------------------------------------------------------------===//
// SILBuilder
//===----------------------------------------------------------------------===//
BridgedInstruction SILBuilder_createBuiltinBinaryFunction(
BridgedBuilder b, StringRef name,
BridgedType operandType, BridgedType resultType,
BridgedValueArray arguments) {
SILBuilder builder(castToInst(b.insertBefore), castToBasicBlock(b.insertAtEnd),
getSILDebugScope(b.loc));
SmallVector<SILValue, 16> argValues;
return {builder.createBuiltinBinaryFunction(getRegularLocation(b.loc),
name, getSILType(operandType), getSILType(resultType),
getSILValues(arguments, argValues))};
}
BridgedInstruction SILBuilder_createCondFail(BridgedBuilder b,
BridgedValue condition, StringRef message) {
SILBuilder builder(castToInst(b.insertBefore), castToBasicBlock(b.insertAtEnd),
getSILDebugScope(b.loc));
return {builder.createCondFail(getRegularLocation(b.loc),
castToSILValue(condition), message)};
}
BridgedInstruction SILBuilder_createIntegerLiteral(BridgedBuilder b,
BridgedType type, SwiftInt value) {
SILBuilder builder(castToInst(b.insertBefore), castToBasicBlock(b.insertAtEnd),
getSILDebugScope(b.loc));
return {builder.createIntegerLiteral(getRegularLocation(b.loc),
getSILType(type), value)};
}
BridgedInstruction SILBuilder_createDeallocStackRef(BridgedBuilder b,
BridgedValue operand) {
SILBuilder builder(castToInst(b.insertBefore), castToBasicBlock(b.insertAtEnd),
getSILDebugScope(b.loc));
return {builder.createDeallocStackRef(getRegularLocation(b.loc),
castToSILValue(operand))};
}
BridgedInstruction
SILBuilder_createUncheckedRefCast(BridgedBuilder b,
BridgedValue op,
BridgedType type) {
SILBuilder builder(castToInst(b.insertBefore), castToBasicBlock(b.insertAtEnd),
getSILDebugScope(b.loc));
return {builder.createUncheckedRefCast(getRegularLocation(b.loc),
castToSILValue(op), getSILType(type))};
}
BridgedInstruction SILBuilder_createSetDeallocating(BridgedBuilder b,
BridgedValue op, bool isAtomic) {
SILBuilder builder(castToInst(b.insertBefore), castToBasicBlock(b.insertAtEnd),
getSILDebugScope(b.loc));
return {builder.createSetDeallocating(
getRegularLocation(b.loc), castToSILValue(op),
isAtomic ? RefCountingInst::Atomicity::Atomic
: RefCountingInst::Atomicity::NonAtomic)};
}
BridgedInstruction
SILBuilder_createFunctionRef(BridgedBuilder b,
BridgedFunction function) {
SILBuilder builder(castToInst(b.insertBefore), castToBasicBlock(b.insertAtEnd),
getSILDebugScope(b.loc));
return {builder.createFunctionRef(getRegularLocation(b.loc),
castToFunction(function))};
}
BridgedInstruction SILBuilder_createCopyValue(BridgedBuilder b,
BridgedValue op) {
SILBuilder builder(castToInst(b.insertBefore), castToBasicBlock(b.insertAtEnd),
getSILDebugScope(b.loc));
return {builder.createCopyValue(getRegularLocation(b.loc),
castToSILValue(op))};
}
BridgedInstruction SILBuilder_createDestroyValue(BridgedBuilder b,
BridgedValue op) {
SILBuilder builder(castToInst(b.insertBefore), castToBasicBlock(b.insertAtEnd),
getSILDebugScope(b.loc));
return {builder.createDestroyValue(getRegularLocation(b.loc),
castToSILValue(op))};
}
BridgedInstruction SILBuilder_createApply(BridgedBuilder b,
BridgedValue function,
BridgedSubstitutionMap subMap,
BridgedValueArray arguments) {
SILBuilder builder(castToInst(b.insertBefore), castToBasicBlock(b.insertAtEnd),
getSILDebugScope(b.loc));
SmallVector<SILValue, 16> argValues;
return {builder.createApply(getRegularLocation(b.loc), castToSILValue(function),
castToSubstitutionMap(subMap),
getSILValues(arguments, argValues))};
}
static EnumElementDecl *getEnumElement(SILType enumType, int caseIndex) {
EnumDecl *enumDecl = enumType.getEnumOrBoundGenericEnum();
for (auto elemWithIndex : llvm::enumerate(enumDecl->getAllElements())) {
if ((int)elemWithIndex.index() == caseIndex)
return elemWithIndex.value();
}
llvm_unreachable("invalid enum case index");
}
BridgedInstruction SILBuilder_createUncheckedEnumData(BridgedBuilder b,
BridgedValue enumVal, SwiftInt caseIdx,
BridgedType resultType) {
SILBuilder builder(castToInst(b.insertBefore), castToBasicBlock(b.insertAtEnd),
getSILDebugScope(b.loc));
SILValue en = castToSILValue(enumVal);
return {builder.createUncheckedEnumData(getRegularLocation(b.loc),
castToSILValue(enumVal),
getEnumElement(en->getType(), caseIdx),
castToSILType(resultType))};
}
BridgedInstruction SILBuilder_createSwitchEnumInst(BridgedBuilder b,
BridgedValue enumVal,
OptionalBridgedBasicBlock defaultBlock,
const void * _Nullable enumCases,
SwiftInt numEnumCases) {
SILBuilder builder(castToInst(b.insertBefore), castToBasicBlock(b.insertAtEnd),
getSILDebugScope(b.loc));
using BridgedCase = const std::pair<SwiftInt, BridgedBasicBlock>;
ArrayRef<BridgedCase> cases(static_cast<BridgedCase *>(enumCases),
(unsigned)numEnumCases);
llvm::SmallDenseMap<SwiftInt, EnumElementDecl *> mappedElements;
SILValue en = castToSILValue(enumVal);
EnumDecl *enumDecl = en->getType().getEnumOrBoundGenericEnum();
for (auto elemWithIndex : llvm::enumerate(enumDecl->getAllElements())) {
mappedElements[elemWithIndex.index()] = elemWithIndex.value();
}
SmallVector<std::pair<EnumElementDecl *, SILBasicBlock *>, 16> convertedCases;
for (auto c : cases) {
assert(mappedElements.count(c.first) && "wrong enum element index");
convertedCases.push_back({mappedElements[c.first], castToBasicBlock(c.second)});
}
return {builder.createSwitchEnum(getRegularLocation(b.loc),
castToSILValue(enumVal),
castToBasicBlock(defaultBlock), convertedCases)};
}
BridgedInstruction SILBuilder_createBranch(
BridgedBuilder b, BridgedBasicBlock destBlock,
BridgedValueArray arguments) {
SILBuilder builder(castToInst(b.insertBefore), castToBasicBlock(b.insertAtEnd),
getSILDebugScope(b.loc));
SmallVector<SILValue, 16> argValues;
return {builder.createBranch(getRegularLocation(b.loc),
castToBasicBlock(destBlock), getSILValues(arguments, argValues))};
}