forked from apple/swift
-
Notifications
You must be signed in to change notification settings - Fork 0
/
SILCloner.h
2790 lines (2454 loc) · 116 KB
/
SILCloner.h
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
//===--- SILCloner.h - Defines the SILCloner class --------------*- C++ -*-===//
//
// 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
//
//===----------------------------------------------------------------------===//
//
// This file defines the SILCloner class, used for cloning SIL instructions.
//
//===----------------------------------------------------------------------===//
#ifndef SWIFT_SIL_SILCLONER_H
#define SWIFT_SIL_SILCLONER_H
#include "swift/AST/ProtocolConformance.h"
#include "swift/SIL/SILOpenedArchetypesTracker.h"
#include "swift/SIL/SILBuilder.h"
#include "swift/SIL/SILDebugScope.h"
#include "swift/SIL/SILVisitor.h"
namespace swift {
/// SILCloner - Abstract SIL visitor which knows how to clone instructions and
/// whose behavior can be customized by subclasses via the CRTP. This is meant
/// to be subclassed to implement inlining, function specialization, and other
/// operations requiring cloning (while possibly modifying, at the same time)
/// instruction sequences.
///
/// By default, this visitor will not do anything useful when called on a
/// basic block, or function; subclasses that want to handle those should
/// implement the appropriate visit functions and/or provide other entry points.
template<typename ImplClass>
class SILCloner : protected SILInstructionVisitor<ImplClass> {
friend class SILVisitorBase<ImplClass>;
friend class SILInstructionVisitor<ImplClass>;
protected:
/// MARK: Context shared with CRTP extensions.
SILBuilder Builder;
TypeSubstitutionMap OpenedExistentialSubs;
SILOpenedArchetypesTracker OpenedArchetypesTracker;
private:
/// MARK: Private state hidden from CRTP extensions.
// The old-to-new value map.
llvm::DenseMap<SILValue, SILValue> ValueMap;
/// The old-to-new block map. Some entries may be premapped with original
/// blocks.
llvm::DenseMap<SILBasicBlock*, SILBasicBlock*> BBMap;
// The original blocks in DFS preorder. All blocks in this list are mapped.
// After cloning, this represents the entire cloned CFG.
//
// This could always be rediscovered by the client, but caching it is a
// convenient way to iterate over the cloned region.
SmallVector<SILBasicBlock *, 8> preorderBlocks;
/// Set of basic blocks where unreachable was inserted.
SmallPtrSet<SILBasicBlock *, 32> BlocksWithUnreachables;
// Keep track of the last cloned block in function order. For single block
// regions, this will be the start block.
SILBasicBlock *lastClonedBB = nullptr;
public:
using SILInstructionVisitor<ImplClass>::asImpl;
explicit SILCloner(SILFunction &F,
SILOpenedArchetypesTracker &OpenedArchetypesTracker)
: Builder(F), OpenedArchetypesTracker(OpenedArchetypesTracker) {
Builder.setOpenedArchetypesTracker(&OpenedArchetypesTracker);
}
explicit SILCloner(SILFunction &F) : Builder(F), OpenedArchetypesTracker(&F) {
Builder.setOpenedArchetypesTracker(&OpenedArchetypesTracker);
}
explicit SILCloner(SILGlobalVariable *GlobVar)
: Builder(GlobVar), OpenedArchetypesTracker(nullptr) {}
void clearClonerState() {
ValueMap.clear();
BBMap.clear();
preorderBlocks.clear();
BlocksWithUnreachables.clear();
}
/// Clients of SILCloner who want to know about any newly created
/// instructions can install a SmallVector into the builder to collect them.
void setTrackingList(SmallVectorImpl<SILInstruction*> *II) {
getBuilder().setTrackingList(II);
}
SmallVectorImpl<SILInstruction*> *getTrackingList() {
return getBuilder().getTrackingList();
}
SILBuilder &getBuilder() { return Builder; }
// After cloning, returns a non-null pointer to the last cloned block in
// function order. For single block regions, this will be the start block.
SILBasicBlock *getLastClonedBB() { return lastClonedBB; }
/// Visit all blocks reachable from the given `StartBB` and all instructions
/// in those blocks.
///
/// This is used to clone a region within a function and mutates the original
/// function. `StartBB` cannot be the function entry block.
///
/// The entire CFG is discovered in DFS preorder while cloning non-terminator
/// instructions. `visitTerminator` is called in the same order, but only
/// after mapping all blocks.
void cloneReachableBlocks(SILBasicBlock *startBB,
ArrayRef<SILBasicBlock *> exitBlocks,
SILBasicBlock *insertAfterBB = nullptr,
bool havePrepopulatedFunctionArgs = false);
/// Clone all blocks in this function and all instructions in those
/// blocks.
///
/// This is used to clone an entire function and should not mutate the
/// original function.
///
/// entryArgs must have a SILValue from the cloned function corresponding to
/// each argument in the original function `F`.
///
/// Cloned instructions are inserted starting at the end of clonedEntryBB.
void cloneFunctionBody(SILFunction *F, SILBasicBlock *clonedEntryBB,
ArrayRef<SILValue> entryArgs);
/// MARK: Callback utilities used from CRTP extensions during cloning.
/// These should only be called from within an instruction cloning visitor.
/// Visitor callback that registers a cloned instruction. All the original
/// instruction's results are mapped onto the cloned instruction's results for
/// use within the cloned region.
///
/// CRTP extensions can
/// override the implementation via `postProcess`.
void recordClonedInstruction(SILInstruction *Orig, SILInstruction *Cloned) {
asImpl().postProcess(Orig, Cloned);
assert((Orig->getDebugScope() ? Cloned->getDebugScope() != nullptr : true)
&& "cloned instruction dropped debug scope");
}
/// Visitor callback that maps an original value to an existing value when the
/// original instruction will not be cloned. This is used when the instruction
/// visitor can fold away the cloned instruction, and it skips the usual
/// `postProcess()` callback. recordClonedInstruction() and
/// recordFoldedValue() are the only two ways for a visitor to map an original
/// value to another value for use within the cloned region.
void recordFoldedValue(SILValue origValue, SILValue mappedValue) {
asImpl().mapValue(origValue, mappedValue);
}
/// Mark a block containing an unreachable instruction for use in the `fixUp`
/// callback.
void addBlockWithUnreachable(SILBasicBlock *BB) {
BlocksWithUnreachables.insert(BB);
}
/// Register a re-mapping for opened existentials.
void registerOpenedExistentialRemapping(ArchetypeType *From,
ArchetypeType *To) {
auto result = OpenedExistentialSubs.insert(
std::make_pair(CanArchetypeType(From), CanType(To)));
assert(result.second);
(void)result;
}
/// MARK: Public access to the cloned state, during and after cloning.
/// After cloning, provides a list of all cloned blocks in DFS preorder.
ArrayRef<SILBasicBlock *> originalPreorderBlocks() const {
return preorderBlocks;
}
SILLocation getOpLocation(SILLocation Loc) {
return asImpl().remapLocation(Loc);
}
const SILDebugScope *getOpScope(const SILDebugScope *DS) {
return asImpl().remapScope(DS);
}
SubstitutionMap getOpSubstitutionMap(SubstitutionMap Subs) {
// If we have open existentials to substitute, check whether that's
// relevant to this this particular substitution.
if (!OpenedExistentialSubs.empty()) {
for (auto ty : Subs.getReplacementTypes()) {
// If we found a type containing an opened existential, substitute
// open existentials throughout the substitution map.
if (ty->hasOpenedExistential()) {
Subs = Subs.subst(QueryTypeSubstitutionMapOrIdentity{
OpenedExistentialSubs},
MakeAbstractConformanceForGenericType());
break;
}
}
}
return asImpl().remapSubstitutionMap(Subs).getCanonical();
}
SILType getTypeInClonedContext(SILType Ty) {
auto objectTy = Ty.getASTType();
// Do not substitute opened existential types, if we do not have any.
if (!objectTy->hasOpenedExistential())
return Ty;
// Do not substitute opened existential types, if it is not required.
// This is often the case when cloning basic blocks inside the same
// function.
if (OpenedExistentialSubs.empty())
return Ty;
// Substitute opened existential types, if we have any.
return Ty.subst(
Builder.getModule(),
QueryTypeSubstitutionMapOrIdentity{OpenedExistentialSubs},
MakeAbstractConformanceForGenericType());
}
SILType getOpType(SILType Ty) {
Ty = getTypeInClonedContext(Ty);
return asImpl().remapType(Ty);
}
CanType getASTTypeInClonedContext(Type ty) {
// Do not substitute opened existential types, if we do not have any.
if (!ty->hasOpenedExistential())
return ty->getCanonicalType();
// Do not substitute opened existential types, if it is not required.
// This is often the case when cloning basic blocks inside the same
// function.
if (OpenedExistentialSubs.empty())
return ty->getCanonicalType();
return ty.subst(
QueryTypeSubstitutionMapOrIdentity{OpenedExistentialSubs},
MakeAbstractConformanceForGenericType()
)->getCanonicalType();
}
CanType getOpASTType(CanType ty) {
ty = getASTTypeInClonedContext(ty);
return asImpl().remapASTType(ty);
}
void remapOpenedType(CanOpenedArchetypeType archetypeTy) {
auto existentialTy = archetypeTy->getOpenedExistentialType()->getCanonicalType();
auto replacementTy = OpenedArchetypeType::get(getOpASTType(existentialTy));
registerOpenedExistentialRemapping(archetypeTy, replacementTy);
}
ProtocolConformanceRef getOpConformance(Type ty,
ProtocolConformanceRef conformance) {
// If we have open existentials to substitute, do so now.
if (ty->hasOpenedExistential() && !OpenedExistentialSubs.empty()) {
conformance =
conformance.subst(ty,
QueryTypeSubstitutionMapOrIdentity{
OpenedExistentialSubs},
MakeAbstractConformanceForGenericType());
}
return asImpl().remapConformance(getASTTypeInClonedContext(ty),
conformance);
}
ArrayRef<ProtocolConformanceRef>
getOpConformances(Type ty,
ArrayRef<ProtocolConformanceRef> conformances) {
SmallVector<ProtocolConformanceRef, 4> newConformances;
for (auto conformance : conformances)
newConformances.push_back(getOpConformance(ty, conformance));
return ty->getASTContext().AllocateCopy(newConformances);
}
bool isValueCloned(SILValue OrigValue) const {
return ValueMap.count(OrigValue);
}
/// Return the possibly new value representing the given value within the
/// cloned region.
///
/// Assumes that `isValueCloned` is true.
SILValue getOpValue(SILValue Value) {
return asImpl().getMappedValue(Value);
}
template <size_t N, typename ArrayRefType>
SmallVector<SILValue, N> getOpValueArray(ArrayRefType Values) {
SmallVector<SILValue, N> Ret(Values.size());
for (unsigned i = 0, e = Values.size(); i != e; ++i)
Ret[i] = asImpl().getMappedValue(Values[i]);
return Ret;
}
SILFunction *getOpFunction(SILFunction *Func) {
return asImpl().remapFunction(Func);
}
bool isBlockCloned(SILBasicBlock *OrigBB) const {
auto bbIter = BBMap.find(OrigBB);
if (bbIter == BBMap.end())
return false;
// Exit blocks are mapped to themselves during region cloning.
return bbIter->second != OrigBB;
}
/// Return the new block within the cloned region analagous to the given
/// original block.
///
/// Assumes that `isBlockCloned` is true.
SILBasicBlock *getOpBasicBlock(SILBasicBlock *BB) {
return asImpl().remapBasicBlock(BB);
}
protected:
/// MARK: CRTP visitors and other CRTP overrides.
#define INST(CLASS, PARENT) void visit##CLASS(CLASS *I);
#include "swift/SIL/SILNodes.def"
// Visit the instructions in a single basic block, not including the block
// terminator.
void visitInstructionsInBlock(SILBasicBlock *BB);
// Visit a block's terminator. This is called with each block in DFS preorder
// after visiting and mapping all basic blocks and after visiting all
// non-terminator instructions in the block.
void visitTerminator(SILBasicBlock *BB) {
asImpl().visit(BB->getTerminator());
}
// CFG cloning requires cloneFunction() or cloneReachableBlocks().
void visitSILBasicBlock(SILFunction *F) = delete;
// Function cloning requires cloneFunction().
void visitSILFunction(SILFunction *F) = delete;
// MARK: SILCloner subclasses use the CRTP to customize the following callback
// implementations. Remap functions are called before cloning to modify
// constructor arguments. The postProcess function is called afterwards on
// the result.
SILLocation remapLocation(SILLocation Loc) { return Loc; }
const SILDebugScope *remapScope(const SILDebugScope *DS) { return DS; }
SILType remapType(SILType Ty) { return Ty; }
CanType remapASTType(CanType Ty) { return Ty; }
ProtocolConformanceRef remapConformance(Type Ty, ProtocolConformanceRef C) {
return C;
}
/// Get the value that takes the place of the given `Value` within the cloned
/// region. The given value must already have been mapped by this cloner.
SILValue getMappedValue(SILValue Value);
void mapValue(SILValue origValue, SILValue mappedValue);
SILFunction *remapFunction(SILFunction *Func) { return Func; }
SILBasicBlock *remapBasicBlock(SILBasicBlock *BB);
void postProcess(SILInstruction *Orig, SILInstruction *Cloned);
SubstitutionMap remapSubstitutionMap(SubstitutionMap Subs) { return Subs; }
/// This is called by either of the top-level visitors, cloneReachableBlocks
/// or cloneSILFunction, after all other visitors are have been called.
///
/// After fixUp, the SIL must be valid and semantically equivalent to the SIL
/// before cloning.
///
/// Common fix-ups are handled first in `doFixUp` and may not be overridden.
void fixUp(SILFunction *F) {}
private:
/// MARK: SILCloner implementation details hidden from CRTP extensions.
/// SILVisitor CRTP callback. Preprocess any instruction before cloning.
void beforeVisit(SILInstruction *Orig) {
// Update the set of available opened archetypes with the opened
// archetypes used by the current instruction.
auto TypeDependentOperands = Orig->getTypeDependentOperands();
Builder.getOpenedArchetypes().addOpenedArchetypeOperands(
TypeDependentOperands);
}
void clonePhiArgs(SILBasicBlock *oldBB);
void visitBlocksDepthFirst(SILBasicBlock *StartBB);
/// Also perform fundamental cleanup first, then call the CRTP extension,
/// `fixUp`.
void doFixUp(SILFunction *F);
};
/// A SILBuilder that automatically invokes postprocess on each
/// inserted instruction.
template<class SomeSILCloner, unsigned N = 4>
class SILBuilderWithPostProcess : public SILBuilder {
SomeSILCloner &SC;
SILInstruction *Orig;
SmallVector<SILInstruction*, N> InsertedInstrs;
public:
SILBuilderWithPostProcess(SomeSILCloner *sc, SILInstruction *Orig)
: SILBuilder(sc->getBuilder().getInsertionBB(), &InsertedInstrs),
SC(*sc), Orig(Orig)
{
setInsertionPoint(SC.getBuilder().getInsertionBB(),
SC.getBuilder().getInsertionPoint());
setOpenedArchetypesTracker(SC.getBuilder().getOpenedArchetypesTracker());
}
~SILBuilderWithPostProcess() {
for (auto *I : InsertedInstrs) {
SC.recordClonedInstruction(Orig, I);
}
}
};
/// SILClonerWithScopes - a SILCloner that automatically clones
/// SILDebugScopes. In contrast to inline scopes, this generates a
/// deep copy of the scope tree.
template<typename ImplClass>
class SILClonerWithScopes : public SILCloner<ImplClass> {
friend class SILCloner<ImplClass>;
public:
SILClonerWithScopes(SILFunction &To,
SILOpenedArchetypesTracker &OpenedArchetypesTracker,
bool Disable = false)
: SILCloner<ImplClass>(To, OpenedArchetypesTracker) {
// We only want to do this when we generate cloned functions, not
// when we inline.
// FIXME: This is due to having TypeSubstCloner inherit from
// SILClonerWithScopes, and having TypeSubstCloner be used
// both by passes that clone whole functions and ones that
// inline functions.
if (Disable)
return;
scopeCloner.reset(new ScopeCloner(To));
}
SILClonerWithScopes(SILFunction &To,
bool Disable = false)
: SILCloner<ImplClass>(To) {
// We only want to do this when we generate cloned functions, not
// when we inline.
// FIXME: This is due to having TypeSubstCloner inherit from
// SILClonerWithScopes, and having TypeSubstCloner be used
// both by passes that clone whole functions and ones that
// inline functions.
if (Disable)
return;
scopeCloner.reset(new ScopeCloner(To));
}
private:
std::unique_ptr<ScopeCloner> scopeCloner;
protected:
/// Clone the SILDebugScope for the cloned function.
void postProcess(SILInstruction *Orig, SILInstruction *Cloned) {
SILCloner<ImplClass>::postProcess(Orig, Cloned);
}
const SILDebugScope *remapScope(const SILDebugScope *DS) {
return scopeCloner ? scopeCloner->getOrCreateClonedScope(DS) : DS;
}
};
/// Clone a function without transforming it.
class SILFunctionCloner : public SILClonerWithScopes<SILFunctionCloner> {
using SuperTy = SILClonerWithScopes<SILFunctionCloner>;
friend class SILCloner<SILFunctionCloner>;
public:
SILFunctionCloner(SILFunction *newF) : SILClonerWithScopes(*newF) {}
/// Clone all blocks in this function and all instructions in those
/// blocks.
///
/// This is used to clone an entire function without mutating the original
/// function.
///
/// The new function is expected to be completely empty. Clone the entry
/// blocks arguments here. The cloned arguments become the inputs to the
/// general SILCloner, which expects the new entry block to be ready to emit
/// instructions into.
void cloneFunction(SILFunction *origF) {
SILFunction *newF = &Builder.getFunction();
auto *newEntryBB = newF->createBasicBlock();
newEntryBB->cloneArgumentList(origF->getEntryBlock());
// Copy the new entry block arguments into a separate vector purely to
// resolve the type mismatch between SILArgument* and SILValue.
SmallVector<SILValue, 8> entryArgs;
entryArgs.reserve(newF->getArguments().size());
llvm::transform(newF->getArguments(), std::back_inserter(entryArgs),
[](SILArgument *arg) -> SILValue { return arg; });
SuperTy::cloneFunctionBody(origF, newEntryBB, entryArgs);
}
};
template<typename ImplClass>
SILValue
SILCloner<ImplClass>::getMappedValue(SILValue Value) {
auto VI = ValueMap.find(Value);
if (VI != ValueMap.end())
return VI->second;
// If we have undef, just remap the type.
if (auto *U = dyn_cast<SILUndef>(Value)) {
auto type = getOpType(U->getType());
ValueBase *undef =
(type == U->getType() ? U : SILUndef::get(type, Builder.getFunction()));
return SILValue(undef);
}
llvm_unreachable("Unmapped value while cloning?");
}
template <typename ImplClass>
void SILCloner<ImplClass>::mapValue(SILValue origValue, SILValue mappedValue) {
auto iterAndInserted = ValueMap.insert({origValue, mappedValue});
(void)iterAndInserted;
assert(iterAndInserted.second && "Original value already mapped.");
}
template<typename ImplClass>
SILBasicBlock*
SILCloner<ImplClass>::remapBasicBlock(SILBasicBlock *BB) {
SILBasicBlock *MappedBB = BBMap[BB];
assert(MappedBB && "Unmapped basic block while cloning?");
return MappedBB;
}
template<typename ImplClass>
void
SILCloner<ImplClass>::postProcess(SILInstruction *orig,
SILInstruction *cloned) {
assert((orig->getDebugScope() ? cloned->getDebugScope()!=nullptr : true) &&
"cloned function dropped debug scope");
// It sometimes happens that an instruction with no results gets mapped
// to an instruction with results, e.g. when specializing a cast.
// Just ignore this.
auto origResults = orig->getResults();
if (origResults.empty()) return;
// Otherwise, map the results over one-by-one.
auto clonedResults = cloned->getResults();
assert(origResults.size() == clonedResults.size());
for (auto i : indices(origResults))
asImpl().mapValue(origResults[i], clonedResults[i]);
}
template<typename ImplClass>
void SILCloner<ImplClass>::visitInstructionsInBlock(SILBasicBlock* BB) {
// Iterate over and visit all instructions other than the terminator to clone.
for (auto I = BB->begin(), E = --BB->end(); I != E; ++I) {
asImpl().visit(&*I);
}
}
template <typename ImplClass>
void SILCloner<ImplClass>::cloneReachableBlocks(
SILBasicBlock *startBB, ArrayRef<SILBasicBlock *> exitBlocks,
SILBasicBlock *insertAfterBB,
bool havePrepopulatedFunctionArgs) {
SILFunction *F = startBB->getParent();
assert(F == &Builder.getFunction()
&& "cannot clone region across functions.");
assert(BBMap.empty() && "This API does not allow clients to map blocks.");
assert((havePrepopulatedFunctionArgs || ValueMap.empty()) &&
"Stale ValueMap.");
auto *clonedStartBB = insertAfterBB ? F->createBasicBlockAfter(insertAfterBB)
: F->createBasicBlock();
BBMap.insert(std::make_pair(startBB, clonedStartBB));
getBuilder().setInsertionPoint(clonedStartBB);
clonePhiArgs(startBB);
// Premap exit blocks to terminate so that visitBlocksDepthFirst terminates
// after discovering the cloned region. Mapping an exit block to itself
// provides the correct destination block during visitTerminator.
for (auto *exitBB : exitBlocks)
BBMap[exitBB] = exitBB;
// Discover and map the region to be cloned.
visitBlocksDepthFirst(startBB);
doFixUp(F);
}
template <typename ImplClass>
void SILCloner<ImplClass>::cloneFunctionBody(SILFunction *F,
SILBasicBlock *clonedEntryBB,
ArrayRef<SILValue> entryArgs) {
assert(F != clonedEntryBB->getParent() && "Must clone into a new function.");
assert(BBMap.empty() && "This API does not allow clients to map blocks.");
assert(ValueMap.empty() && "Stale ValueMap.");
assert(entryArgs.size() == F->getArguments().size());
for (unsigned i = 0, e = entryArgs.size(); i != e; ++i)
ValueMap[F->getArgument(i)] = entryArgs[i];
BBMap.insert(std::make_pair(&*F->begin(), clonedEntryBB));
Builder.setInsertionPoint(clonedEntryBB);
// This will layout all newly cloned blocks immediate after clonedEntryBB.
visitBlocksDepthFirst(&*F->begin());
doFixUp(F);
}
template<typename ImplClass>
void SILCloner<ImplClass>::clonePhiArgs(SILBasicBlock *oldBB) {
auto *mappedBB = BBMap[oldBB];
// Create new arguments for each of the original block's arguments.
for (auto *Arg : oldBB->getPhiArguments()) {
SILValue mappedArg = mappedBB->createPhiArgument(
getOpType(Arg->getType()), Arg->getOwnershipKind());
asImpl().mapValue(Arg, mappedArg);
}
}
// This private helper visits BBs in depth-first preorder (only processing
// blocks on the first visit), mapping newly visited BBs to new BBs and cloning
// all instructions into the caller.
template <typename ImplClass>
void SILCloner<ImplClass>::visitBlocksDepthFirst(SILBasicBlock *startBB) {
// The caller clones startBB because it may be a function header, which
// requires special handling.
assert(BBMap.count(startBB) && "The caller must map the first BB.");
assert(preorderBlocks.empty());
// First clone the CFG region.
//
// FIXME: Add reverse iteration to SILSuccessor, then convert this to an RPOT
// traversal. We would prefer to keep CFG regions in RPO order, and this would
// not create as large a worklist for functions with many large switches.
SmallVector<SILBasicBlock *, 8> dfsWorklist(1, startBB);
// Keep a reference to the last cloned BB so blocks can be laid out in the
// order they are created, which differs from the order they are
// cloned. Blocks are created in BFS order but cloned in DFS preorder (when no
// critical edges are present).
lastClonedBB = BBMap[startBB];
while (!dfsWorklist.empty()) {
auto *BB = dfsWorklist.pop_back_val();
preorderBlocks.push_back(BB);
// Phis are cloned during the first preorder walk so that successor phis
// exist before predecessor terminators are generated.
if (BB != startBB)
clonePhiArgs(BB);
// Non-terminating instructions are cloned in the first preorder walk so
// that all opened existentials are registered with OpenedArchetypesTracker
// before phi argument type substitution in successors.
getBuilder().setInsertionPoint(BBMap[BB]);
asImpl().visitInstructionsInBlock(BB);
unsigned dfsSuccStartIdx = dfsWorklist.size();
for (auto &succ : BB->getSuccessors()) {
// Only visit a successor that has not already been visited and was not
// premapped by the client.
if (BBMap.count(succ))
continue;
// Map the successor to a new BB. Layout the cloned blocks in the order
// they are visited and cloned.
lastClonedBB =
getBuilder().getFunction().createBasicBlockAfter(lastClonedBB);
BBMap.insert(std::make_pair(succ.getBB(), lastClonedBB));
dfsWorklist.push_back(succ);
}
// Reverse the worklist to pop the successors in forward order. This
// precisely yields DFS preorder when no critical edges are present.
std::reverse(dfsWorklist.begin() + dfsSuccStartIdx, dfsWorklist.end());
}
// Visit terminators only after the CFG is valid so all branch targets exist.
//
// Visiting in pre-order provides a nice property for the individual
// instruction visitors. It allows those visitors to make use of dominance
// relationships, particularly the fact that operand values will be mapped.
for (auto *origBB : preorderBlocks) {
// Set the insertion point to the new mapped BB
getBuilder().setInsertionPoint(BBMap[origBB]);
asImpl().visitTerminator(origBB);
}
}
/// Clean-up after cloning.
template<typename ImplClass>
void
SILCloner<ImplClass>::doFixUp(SILFunction *F) {
// If our source function is in ossa form, but the function into which we are
// cloning is not in ossa, after we clone, eliminate default arguments.
if (!getBuilder().hasOwnership() && F->hasOwnership()) {
for (auto &Block : getBuilder().getFunction()) {
auto *Term = Block.getTerminator();
if (auto *CCBI = dyn_cast<CheckedCastBranchInst>(Term)) {
// Check if we have a default argument.
auto *FailureBlock = CCBI->getFailureBB();
assert(FailureBlock->getNumArguments() <= 1 &&
"We should either have no args or a single default arg");
if (0 == FailureBlock->getNumArguments())
continue;
FailureBlock->getArgument(0)->replaceAllUsesWith(CCBI->getOperand());
FailureBlock->eraseArgument(0);
continue;
}
if (auto *SEI = dyn_cast<SwitchEnumInst>(Term)) {
if (auto DefaultBlock = SEI->getDefaultBBOrNull()) {
assert(DefaultBlock.get()->getNumArguments() <= 1 &&
"We should either have no args or a single default arg");
if (0 == DefaultBlock.get()->getNumArguments())
continue;
DefaultBlock.get()->getArgument(0)->replaceAllUsesWith(
SEI->getOperand());
DefaultBlock.get()->eraseArgument(0);
continue;
}
}
}
}
// Remove any code after unreachable instructions.
// NOTE: It is unfortunate that it essentially duplicates the code from
// sil-combine, but doing so allows for avoiding any cross-layer invocations
// between SIL and SILOptimizer layers.
for (auto *BB : BlocksWithUnreachables) {
for (auto &I : *BB) {
if (!isa<UnreachableInst>(&I))
continue;
// Collect together all the instructions after this point
llvm::SmallVector<SILInstruction *, 32> ToRemove;
for (auto Inst = BB->rbegin(); &*Inst != &I; ++Inst)
ToRemove.push_back(&*Inst);
for (auto *Inst : ToRemove) {
// Replace any non-dead results with SILUndef values
Inst->replaceAllUsesOfAllResultsWithUndef();
Inst->eraseFromParent();
}
}
}
BlocksWithUnreachables.clear();
// Call any cleanup specific to the CRTP extensions.
asImpl().fixUp(F);
}
template<typename ImplClass>
void
SILCloner<ImplClass>::visitAllocStackInst(AllocStackInst *Inst) {
getBuilder().setCurrentDebugScope(getOpScope(Inst->getDebugScope()));
recordClonedInstruction(
Inst, getBuilder().createAllocStack(getOpLocation(Inst->getLoc()),
getOpType(Inst->getElementType())));
}
template<typename ImplClass>
void
SILCloner<ImplClass>::visitAllocRefInst(AllocRefInst *Inst) {
getBuilder().setCurrentDebugScope(getOpScope(Inst->getDebugScope()));
auto CountArgs = getOpValueArray<8>(OperandValueArrayRef(Inst->
getTailAllocatedCounts()));
SmallVector<SILType, 4> ElemTypes;
for (SILType OrigElemType : Inst->getTailAllocatedTypes()) {
ElemTypes.push_back(getOpType(OrigElemType));
}
auto *NewInst = getBuilder().createAllocRef(getOpLocation(Inst->getLoc()),
getOpType(Inst->getType()),
Inst->isObjC(), Inst->canAllocOnStack(),
ElemTypes, CountArgs);
recordClonedInstruction(Inst, NewInst);
}
template<typename ImplClass>
void
SILCloner<ImplClass>::visitAllocRefDynamicInst(AllocRefDynamicInst *Inst) {
getBuilder().setCurrentDebugScope(getOpScope(Inst->getDebugScope()));
auto CountArgs = getOpValueArray<8>(OperandValueArrayRef(Inst->
getTailAllocatedCounts()));
SmallVector<SILType, 4> ElemTypes;
for (SILType OrigElemType : Inst->getTailAllocatedTypes()) {
ElemTypes.push_back(getOpType(OrigElemType));
}
auto *NewInst = getBuilder().createAllocRefDynamic(
getOpLocation(Inst->getLoc()),
getOpValue(Inst->getMetatypeOperand()),
getOpType(Inst->getType()),
Inst->isObjC(),
ElemTypes, CountArgs);
recordClonedInstruction(Inst, NewInst);
}
template<typename ImplClass>
void
SILCloner<ImplClass>::visitAllocBoxInst(AllocBoxInst *Inst) {
getBuilder().setCurrentDebugScope(getOpScope(Inst->getDebugScope()));
recordClonedInstruction(
Inst,
getBuilder().createAllocBox(
getOpLocation(Inst->getLoc()),
this->getOpType(Inst->getType()).template castTo<SILBoxType>()));
}
template<typename ImplClass>
void
SILCloner<ImplClass>::visitAllocExistentialBoxInst(
AllocExistentialBoxInst *Inst) {
auto origExistentialType = Inst->getExistentialType();
auto origFormalType = Inst->getFormalConcreteType();
auto conformances = getOpConformances(origFormalType,
Inst->getConformances());
getBuilder().setCurrentDebugScope(getOpScope(Inst->getDebugScope()));
recordClonedInstruction(
Inst, getBuilder().createAllocExistentialBox(
getOpLocation(Inst->getLoc()), getOpType(origExistentialType),
getOpASTType(origFormalType), conformances));
}
template<typename ImplClass>
void
SILCloner<ImplClass>::visitAllocValueBufferInst(AllocValueBufferInst *Inst) {
getBuilder().setCurrentDebugScope(getOpScope(Inst->getDebugScope()));
recordClonedInstruction(Inst, getBuilder().createAllocValueBuffer(
getOpLocation(Inst->getLoc()),
getOpType(Inst->getValueType()),
getOpValue(Inst->getOperand())));
}
template<typename ImplClass>
void
SILCloner<ImplClass>::visitBuiltinInst(BuiltinInst *Inst) {
auto Args = getOpValueArray<8>(Inst->getArguments());
getBuilder().setCurrentDebugScope(getOpScope(Inst->getDebugScope()));
recordClonedInstruction(
Inst, getBuilder().createBuiltin(
getOpLocation(Inst->getLoc()), Inst->getName(),
getOpType(Inst->getType()),
getOpSubstitutionMap(Inst->getSubstitutions()), Args));
}
template<typename ImplClass>
void
SILCloner<ImplClass>::visitApplyInst(ApplyInst *Inst) {
auto Args = getOpValueArray<8>(Inst->getArguments());
getBuilder().setCurrentDebugScope(getOpScope(Inst->getDebugScope()));
recordClonedInstruction(
Inst, getBuilder().createApply(
getOpLocation(Inst->getLoc()), getOpValue(Inst->getCallee()),
getOpSubstitutionMap(Inst->getSubstitutionMap()), Args,
Inst->isNonThrowing(),
GenericSpecializationInformation::create(Inst, getBuilder())));
}
template<typename ImplClass>
void
SILCloner<ImplClass>::visitTryApplyInst(TryApplyInst *Inst) {
auto Args = getOpValueArray<8>(Inst->getArguments());
getBuilder().setCurrentDebugScope(getOpScope(Inst->getDebugScope()));
recordClonedInstruction(
Inst, getBuilder().createTryApply(
getOpLocation(Inst->getLoc()), getOpValue(Inst->getCallee()),
getOpSubstitutionMap(Inst->getSubstitutionMap()), Args,
getOpBasicBlock(Inst->getNormalBB()),
getOpBasicBlock(Inst->getErrorBB()),
GenericSpecializationInformation::create(Inst, getBuilder())));
}
template<typename ImplClass>
void
SILCloner<ImplClass>::visitPartialApplyInst(PartialApplyInst *Inst) {
auto Args = getOpValueArray<8>(Inst->getArguments());
getBuilder().setCurrentDebugScope(getOpScope(Inst->getDebugScope()));
recordClonedInstruction(
Inst, getBuilder().createPartialApply(
getOpLocation(Inst->getLoc()), getOpValue(Inst->getCallee()),
getOpSubstitutionMap(Inst->getSubstitutionMap()), Args,
Inst->getType().getAs<SILFunctionType>()->getCalleeConvention(),
Inst->isOnStack(),
GenericSpecializationInformation::create(Inst, getBuilder())));
}
template<typename ImplClass>
void
SILCloner<ImplClass>::visitBeginApplyInst(BeginApplyInst *Inst) {
auto Args = getOpValueArray<8>(Inst->getArguments());
getBuilder().setCurrentDebugScope(getOpScope(Inst->getDebugScope()));
recordClonedInstruction(
Inst, getBuilder().createBeginApply(
getOpLocation(Inst->getLoc()), getOpValue(Inst->getCallee()),
getOpSubstitutionMap(Inst->getSubstitutionMap()), Args,
Inst->isNonThrowing(),
GenericSpecializationInformation::create(Inst, getBuilder())));
}
template<typename ImplClass>
void
SILCloner<ImplClass>::visitAbortApplyInst(AbortApplyInst *Inst) {
getBuilder().setCurrentDebugScope(getOpScope(Inst->getDebugScope()));
recordClonedInstruction(
Inst, getBuilder().createAbortApply(getOpLocation(Inst->getLoc()),
getOpValue(Inst->getOperand())));
}
template<typename ImplClass>
void
SILCloner<ImplClass>::visitEndApplyInst(EndApplyInst *Inst) {
getBuilder().setCurrentDebugScope(getOpScope(Inst->getDebugScope()));
recordClonedInstruction(
Inst, getBuilder().createEndApply(getOpLocation(Inst->getLoc()),
getOpValue(Inst->getOperand())));
}
template<typename ImplClass>
void
SILCloner<ImplClass>::visitFunctionRefInst(FunctionRefInst *Inst) {
SILFunction *OpFunction =
getOpFunction(Inst->getInitiallyReferencedFunction());
getBuilder().setCurrentDebugScope(getOpScope(Inst->getDebugScope()));
recordClonedInstruction(Inst, getBuilder().createFunctionRef(
getOpLocation(Inst->getLoc()), OpFunction));
}
template<typename ImplClass>
void
SILCloner<ImplClass>::visitDynamicFunctionRefInst(DynamicFunctionRefInst *Inst) {
SILFunction *OpFunction =
getOpFunction(Inst->getInitiallyReferencedFunction());
getBuilder().setCurrentDebugScope(getOpScope(Inst->getDebugScope()));
recordClonedInstruction(Inst, getBuilder().createDynamicFunctionRef(
getOpLocation(Inst->getLoc()), OpFunction));
}
template <typename ImplClass>
void SILCloner<ImplClass>::visitPreviousDynamicFunctionRefInst(
PreviousDynamicFunctionRefInst *Inst) {
SILFunction *OpFunction =
getOpFunction(Inst->getInitiallyReferencedFunction());
getBuilder().setCurrentDebugScope(getOpScope(Inst->getDebugScope()));
recordClonedInstruction(Inst, getBuilder().createPreviousDynamicFunctionRef(
getOpLocation(Inst->getLoc()), OpFunction));
}
template<typename ImplClass>
void
SILCloner<ImplClass>::visitAllocGlobalInst(AllocGlobalInst *Inst) {
getBuilder().setCurrentDebugScope(getOpScope(Inst->getDebugScope()));
recordClonedInstruction(
Inst, getBuilder().createAllocGlobal(getOpLocation(Inst->getLoc()),
Inst->getReferencedGlobal()));
}
template<typename ImplClass>
void
SILCloner<ImplClass>::visitGlobalAddrInst(GlobalAddrInst *Inst) {
getBuilder().setCurrentDebugScope(getOpScope(Inst->getDebugScope()));
recordClonedInstruction(
Inst, getBuilder().createGlobalAddr(getOpLocation(Inst->getLoc()),
Inst->getReferencedGlobal()));
}
template<typename ImplClass>
void
SILCloner<ImplClass>::visitGlobalValueInst(GlobalValueInst *Inst) {