-
Notifications
You must be signed in to change notification settings - Fork 10.4k
/
Copy pathVJPCloner.cpp
1459 lines (1296 loc) · 61.5 KB
/
VJPCloner.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
//===--- VJPCloner.cpp - VJP function generation --------------*- C++ -*---===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2019 - 2020 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 a helper class for generating VJP functions for automatic
// differentiation.
//
//===----------------------------------------------------------------------===//
#define DEBUG_TYPE "differentiation"
#include "swift/AST/Types.h"
#include "swift/Basic/Assertions.h"
#include "swift/SILOptimizer/Differentiation/VJPCloner.h"
#include "swift/SILOptimizer/Analysis/DifferentiableActivityAnalysis.h"
#include "swift/SILOptimizer/Differentiation/ADContext.h"
#include "swift/SILOptimizer/Differentiation/DifferentiationInvoker.h"
#include "swift/SILOptimizer/Differentiation/LinearMapInfo.h"
#include "swift/SILOptimizer/Differentiation/PullbackCloner.h"
#include "swift/SILOptimizer/Differentiation/Thunk.h"
#include "swift/SIL/TerminatorUtils.h"
#include "swift/SIL/TypeSubstCloner.h"
#include "swift/SILOptimizer/Analysis/LoopAnalysis.h"
#include "swift/SILOptimizer/PassManager/PrettyStackTrace.h"
#include "swift/SILOptimizer/Utils/CFGOptUtils.h"
#include "swift/SILOptimizer/Utils/DifferentiationMangler.h"
#include "swift/SILOptimizer/Utils/SILOptFunctionBuilder.h"
#include "llvm/ADT/DenseMap.h"
namespace swift {
namespace autodiff {
class VJPCloner::Implementation final
: public TypeSubstCloner<VJPCloner::Implementation, SILOptFunctionBuilder> {
friend class VJPCloner;
friend class PullbackCloner;
/// The parent VJP cloner.
VJPCloner &cloner;
/// The global context.
ADContext &context;
/// The original function.
SILFunction *const original;
/// The differentiability witness.
SILDifferentiabilityWitness *const witness;
/// The VJP function.
SILFunction *const vjp;
/// The pullback function.
SILFunction *pullback;
/// The differentiation invoker.
DifferentiationInvoker invoker;
/// Info from activity analysis on the original function.
const DifferentiableActivityInfo &activityInfo;
/// The loop info.
SILLoopInfo *loopInfo;
/// The linear map info.
LinearMapInfo pullbackInfo;
/// Caches basic blocks whose phi arguments have been remapped (adding a
/// predecessor enum argument).
SmallPtrSet<SILBasicBlock *, 4> remappedBasicBlocks;
/// The `AutoDiffLinearMapContext` object. If null, no explicit context is
/// needed (no loops).
SILValue pullbackContextValue;
/// The unique, borrowed context object. This is valid until the exit block.
SILValue borrowedPullbackContextValue;
/// The generic signature of the `Builtin.autoDiffAllocateSubcontext(_:_:)`
/// declaration. It is used for creating a builtin call.
GenericSignature builtinAutoDiffAllocateSubcontextGenericSignature;
bool errorOccurred = false;
/// Mapping from original blocks to pullback values. Used to build pullback
/// struct instances.
llvm::DenseMap<SILBasicBlock *, SmallVector<SILValue, 8>> pullbackValues;
ASTContext &getASTContext() const { return vjp->getASTContext(); }
SILModule &getModule() const { return vjp->getModule(); }
const AutoDiffConfig &getConfig() const {
return witness->getConfig();
}
Implementation(VJPCloner &parent, ADContext &context,
SILDifferentiabilityWitness *witness, SILFunction *vjp,
DifferentiationInvoker invoker);
/// Creates an empty pullback function, to be filled in by `PullbackCloner`.
SILFunction *createEmptyPullback();
/// Run VJP generation. Returns true on error.
bool run();
/// Initializes a context object if needed.
void emitLinearMapContextInitializationIfNeeded() {
if (!pullbackInfo.hasHeapAllocatedContext())
return;
// Get linear map struct size.
auto *returnBB = &*original->findReturnBB();
auto pullbackTupleType =
remapASTType(pullbackInfo.getLinearMapTupleType(returnBB)->getCanonicalType());
Builder.setInsertionPoint(vjp->getEntryBlock());
auto pbTupleMetatypeType =
CanMetatypeType::get(pullbackTupleType, MetatypeRepresentation::Thick);
auto pbTupleMetatypeSILType =
SILType::getPrimitiveObjectType(pbTupleMetatypeType);
auto pbTupleMetatype =
Builder.createMetatype(original->getLocation(), pbTupleMetatypeSILType);
// Create an context.
pullbackContextValue = Builder.createBuiltin(
original->getLocation(),
getASTContext().getIdentifier(getBuiltinName(
BuiltinValueKind::AutoDiffCreateLinearMapContextWithType)),
SILType::getNativeObjectType(getASTContext()), SubstitutionMap(),
{pbTupleMetatype});
borrowedPullbackContextValue = Builder.createBeginBorrow(
original->getLocation(), pullbackContextValue);
LLVM_DEBUG(getADDebugStream()
<< "Context object initialized because there are loops\n"
<< *vjp->getEntryBlock() << '\n'
<< "pullback tuple type: " << pullbackTupleType << '\n');
}
/// Get the lowered SIL type of the given AST type.
SILType getLoweredType(Type type) {
auto vjpGenSig = vjp->getLoweredFunctionType()->getSubstGenericSignature();
Lowering::AbstractionPattern pattern(vjpGenSig,
type->getReducedType(vjpGenSig));
return vjp->getLoweredType(pattern, type);
}
SILType getPullbackType() {
auto vjpFuncTy = vjp->getLoweredFunctionType();
const auto &conv = vjp->getConventions();
return conv.getSILType(vjpFuncTy->getResults().back(),
vjp->getTypeExpansionContext());
}
GenericSignature getBuiltinAutoDiffAllocateSubcontextDecl() {
if (builtinAutoDiffAllocateSubcontextGenericSignature)
return builtinAutoDiffAllocateSubcontextGenericSignature;
auto &ctx = getASTContext();
auto *decl = cast<FuncDecl>(getBuiltinValueDecl(
ctx, ctx.getIdentifier(getBuiltinName(
BuiltinValueKind::AutoDiffAllocateSubcontextWithType))));
builtinAutoDiffAllocateSubcontextGenericSignature =
decl->getGenericSignature();
assert(builtinAutoDiffAllocateSubcontextGenericSignature);
return builtinAutoDiffAllocateSubcontextGenericSignature;
}
// Creates a trampoline block for given original terminator instruction, the
// pullback struct value for its parent block, and a successor basic block.
//
// The trampoline block has the same arguments as and branches to the remapped
// successor block, but drops the last predecessor enum argument.
//
// Used for cloning branching terminator instructions with specific
// requirements on successor block arguments, where an additional predecessor
// enum argument is not acceptable.
SILBasicBlock *createTrampolineBasicBlock(TermInst *termInst,
TupleInst *pbTupleVal,
SILBasicBlock *succBB);
/// Build a pullback tuple value for the given original terminator
/// instruction.
TupleInst *buildPullbackValueTupleValue(TermInst *termInst);
llvm::SmallVector<SILValue, 8> getPullbackValues(SILBasicBlock *origBB);
/// Build a predecessor enum instance using the given builder for the given
/// original predecessor/successor blocks and pullback struct value.
EnumInst *buildPredecessorEnumValue(SILBuilder &builder,
SILBasicBlock *predBB,
SILBasicBlock *succBB,
SILValue pbTupleVal);
public:
/// Remap original basic blocks, adding predecessor enum arguments.
SILBasicBlock *remapBasicBlock(SILBasicBlock *bb) {
auto *vjpBB = BBMap[bb];
// If error has occurred, or if block has already been remapped, return
// remapped, return remapped block.
if (errorOccurred || remappedBasicBlocks.count(bb))
return vjpBB;
// Add predecessor enum argument to the remapped block.
auto *predEnum = pullbackInfo.getBranchingTraceDecl(bb);
auto enumTy =
getOpASTType(predEnum->getDeclaredInterfaceType()->getCanonicalType());
auto enumLoweredTy = context.getTypeConverter().getLoweredType(
enumTy, TypeExpansionContext::minimal());
vjpBB->createPhiArgument(enumLoweredTy, OwnershipKind::Owned);
remappedBasicBlocks.insert(bb);
return vjpBB;
}
/// General visitor for all instructions. If any error is emitted by previous
/// visits, bail out.
void visit(SILInstruction *inst) {
if (errorOccurred)
return;
TypeSubstCloner::visit(inst);
}
void visitSILInstruction(SILInstruction *inst) {
context.emitNondifferentiabilityError(
inst, invoker, diag::autodiff_expression_not_differentiable_note);
errorOccurred = true;
}
void postProcess(SILInstruction *orig, SILInstruction *cloned) {
if (errorOccurred)
return;
SILClonerWithScopes::postProcess(orig, cloned);
}
void visitReturnInst(ReturnInst *ri) {
Builder.setCurrentDebugScope(getOpScope(ri->getDebugScope()));
auto loc = ri->getOperand().getLoc();
// Build pullback tuple value for original block.
auto *origExit = ri->getParent();
// Get the value in the VJP corresponding to the original result.
auto *origRetInst = cast<ReturnInst>(origExit->getTerminator());
auto origResult = getOpValue(origRetInst->getOperand());
SmallVector<SILValue, 8> origResults;
extractAllElements(origResult, Builder, origResults);
// Get and partially apply the pullback.
auto vjpSubstMap = vjp->getForwardingSubstitutionMap();
auto *pullbackRef = Builder.createFunctionRef(loc, pullback);
// Prepare partial application arguments.
SILValue partialApplyArg;
PartialApplyInst *pullbackPartialApply;
if (borrowedPullbackContextValue) {
auto *pbTupleVal = buildPullbackValueTupleValue(ri);
// Initialize the top-level subcontext buffer with the top-level pullback
// tuple.
auto addr = emitProjectTopLevelSubcontext(
Builder, loc, borrowedPullbackContextValue, pbTupleVal->getType());
Builder.createStore(
loc, pbTupleVal, addr,
pbTupleVal->getType().isTrivial(*pullback) ?
StoreOwnershipQualifier::Trivial : StoreOwnershipQualifier::Init);
Builder.createEndBorrow(loc, borrowedPullbackContextValue);
pullbackPartialApply = Builder.createPartialApply(
loc, pullbackRef, vjpSubstMap, {pullbackContextValue},
ParameterConvention::Direct_Guaranteed);
} else {
pullbackPartialApply = Builder.createPartialApply(
loc, pullbackRef, vjpSubstMap, getPullbackValues(origExit),
ParameterConvention::Direct_Guaranteed);
}
auto pullbackType = vjp->mapTypeIntoContext(getPullbackType());
auto pullbackFnType = pullbackType.castTo<SILFunctionType>();
auto pullbackSubstType =
pullbackPartialApply->getType().castTo<SILFunctionType>();
// If necessary, convert the pullback value to the returned pullback
// function type.
SILValue pullbackValue;
if (pullbackSubstType == pullbackFnType) {
pullbackValue = pullbackPartialApply;
} else if (pullbackSubstType->isABICompatibleWith(pullbackFnType, *vjp)
.isCompatible()) {
pullbackValue =
Builder.createConvertFunction(loc, pullbackPartialApply, pullbackType,
/*withoutActuallyEscaping*/ false);
} else {
llvm::report_fatal_error("Pullback value type is not ABI-compatible "
"with the returned pullback type");
}
// Return a tuple of the original result and pullback.
SmallVector<SILValue, 8> directResults;
directResults.append(origResults.begin(), origResults.end());
directResults.push_back(pullbackValue);
Builder.createReturn(ri->getLoc(),
joinElements(directResults, Builder, loc));
}
void visitUnwindInst(UnwindInst *ui) {
Builder.setCurrentDebugScope(getOpScope(ui->getDebugScope()));
auto loc = ui->getLoc();
auto *origExit = ui->getParent();
// Consume unused pullback values
if (borrowedPullbackContextValue) {
auto *pbTupleVal = buildPullbackValueTupleValue(ui);
// Initialize the top-level subcontext buffer with the top-level pullback
// tuple.
auto addr = emitProjectTopLevelSubcontext(
Builder, loc, borrowedPullbackContextValue, pbTupleVal->getType());
Builder.createStore(
loc, pbTupleVal, addr,
pbTupleVal->getType().isTrivial(*pullback) ?
StoreOwnershipQualifier::Trivial : StoreOwnershipQualifier::Init);
Builder.createEndBorrow(loc, borrowedPullbackContextValue);
Builder.emitDestroyValueOperation(loc, pullbackContextValue);
} else {
for (SILValue val : getPullbackValues(origExit))
Builder.emitDestroyValueOperation(loc, val);
}
Builder.createUnwind(loc);
}
void visitBranchInst(BranchInst *bi) {
Builder.setCurrentDebugScope(getOpScope(bi->getDebugScope()));
// Build pullback struct value for original block.
// Build predecessor enum value for destination block.
auto *origBB = bi->getParent();
auto *pbTupleVal = buildPullbackValueTupleValue(bi);
auto *enumVal = buildPredecessorEnumValue(getBuilder(), origBB,
bi->getDestBB(), pbTupleVal);
// Remap arguments, appending the new enum values.
SmallVector<SILValue, 8> args;
for (auto origArg : bi->getArgs())
args.push_back(getOpValue(origArg));
args.push_back(enumVal);
// Create a new `br` instruction.
getBuilder().createBranch(bi->getLoc(), getOpBasicBlock(bi->getDestBB()),
args);
}
void visitYieldInst(YieldInst *yi) {
Builder.setCurrentDebugScope(getOpScope(yi->getDebugScope()));
// Build pullback struct value for original block.
auto *pbTupleVal = buildPullbackValueTupleValue(yi);
// Create a new `yield` instruction. Note that resume / unwind blocks cannot
// have arguments, so we're building trampolines with branch tracing enum
// values.
getBuilder().createYield(
yi->getLoc(), getOpValueArray<1>(yi->getOperandValues()),
createTrampolineBasicBlock(yi, pbTupleVal, yi->getResumeBB()),
createTrampolineBasicBlock(yi, pbTupleVal, yi->getUnwindBB()));
}
void visitCondBranchInst(CondBranchInst *cbi) {
Builder.setCurrentDebugScope(getOpScope(cbi->getDebugScope()));
// Build pullback struct value for original block.
auto *pbTupleVal = buildPullbackValueTupleValue(cbi);
// Create a new `cond_br` instruction.
getBuilder().createCondBranch(
cbi->getLoc(), getOpValue(cbi->getCondition()),
createTrampolineBasicBlock(cbi, pbTupleVal, cbi->getTrueBB()),
createTrampolineBasicBlock(cbi, pbTupleVal, cbi->getFalseBB()));
}
void visitSwitchEnumTermInst(SwitchEnumTermInst inst) {
Builder.setCurrentDebugScope(getOpScope(inst->getDebugScope()));
// Build pullback tuple value for original block.
auto *pbTupleVal = buildPullbackValueTupleValue(*inst);
// Create trampoline successor basic blocks.
SmallVector<std::pair<EnumElementDecl *, SILBasicBlock *>, 4> caseBBs;
for (unsigned i : range(inst.getNumCases())) {
auto caseBB = inst.getCase(i);
auto *trampolineBB =
createTrampolineBasicBlock(inst, pbTupleVal, caseBB.second);
caseBBs.push_back({caseBB.first, trampolineBB});
}
// Create trampoline default basic block.
SILBasicBlock *newDefaultBB = nullptr;
if (auto *defaultBB = inst.getDefaultBBOrNull().getPtrOrNull())
newDefaultBB = createTrampolineBasicBlock(inst, pbTupleVal, defaultBB);
// Create a new `switch_enum` instruction.
switch (inst->getKind()) {
case SILInstructionKind::SwitchEnumInst:
getBuilder().createSwitchEnum(
inst->getLoc(), getOpValue(inst.getOperand()), newDefaultBB, caseBBs);
break;
case SILInstructionKind::SwitchEnumAddrInst:
getBuilder().createSwitchEnumAddr(
inst->getLoc(), getOpValue(inst.getOperand()), newDefaultBB, caseBBs);
break;
default:
llvm_unreachable("Expected `switch_enum` or `switch_enum_addr`");
}
}
void visitSwitchEnumInst(SwitchEnumInst *sei) {
visitSwitchEnumTermInst(sei);
}
void visitSwitchEnumAddrInst(SwitchEnumAddrInst *seai) {
visitSwitchEnumTermInst(seai);
}
void visitCheckedCastBranchInst(CheckedCastBranchInst *ccbi) {
Builder.setCurrentDebugScope(getOpScope(ccbi->getDebugScope()));
// Build pullback struct value for original block.
auto *pbTupleVal = buildPullbackValueTupleValue(ccbi);
// Create a new `checked_cast_branch` instruction.
getBuilder().createCheckedCastBranch(
ccbi->getLoc(), ccbi->isExact(), getOpValue(ccbi->getOperand()),
getOpASTType(ccbi->getSourceFormalType()),
getOpType(ccbi->getTargetLoweredType()),
getOpASTType(ccbi->getTargetFormalType()),
createTrampolineBasicBlock(ccbi, pbTupleVal, ccbi->getSuccessBB()),
createTrampolineBasicBlock(ccbi, pbTupleVal, ccbi->getFailureBB()),
ccbi->getTrueBBCount(), ccbi->getFalseBBCount());
}
void visitCheckedCastAddrBranchInst(CheckedCastAddrBranchInst *ccabi) {
Builder.setCurrentDebugScope(getOpScope(ccabi->getDebugScope()));
// Build pullback struct value for original block.
auto *pbTupleVal = buildPullbackValueTupleValue(ccabi);
// Create a new `checked_cast_addr_branch` instruction.
getBuilder().createCheckedCastAddrBranch(
ccabi->getLoc(), ccabi->getConsumptionKind(),
getOpValue(ccabi->getSrc()), getOpASTType(ccabi->getSourceFormalType()),
getOpValue(ccabi->getDest()),
getOpASTType(ccabi->getTargetFormalType()),
createTrampolineBasicBlock(ccabi, pbTupleVal, ccabi->getSuccessBB()),
createTrampolineBasicBlock(ccabi, pbTupleVal, ccabi->getFailureBB()),
ccabi->getTrueBBCount(), ccabi->getFalseBBCount());
}
void visitEndApplyInst(EndApplyInst *eai) {
BeginApplyInst *bai = eai->getBeginApply();
// If callee should not be differentiated, do standard cloning.
if (!pullbackInfo.shouldDifferentiateApplySite(bai)) {
LLVM_DEBUG(getADDebugStream() << "No active results:\n" << *bai << '\n');
TypeSubstCloner::visitEndApplyInst(eai);
return;
}
Builder.setCurrentDebugScope(getOpScope(eai->getDebugScope()));
auto loc = eai->getLoc();
auto &builder = getBuilder();
auto token = getMappedValue(bai->getTokenResult());
LLVM_DEBUG(getADDebugStream() << "VJP-transforming:\n" << *eai << '\n');
FullApplySite fai(token->getDefiningInstruction());
auto vjpResult = builder.createEndApply(loc, token, fai.getType());
LLVM_DEBUG(getADDebugStream() << "Created end_apply\n" << *vjpResult);
builder.emitDestroyValueOperation(loc, fai.getCallee());
// Checkpoint the pullback.
SmallVector<SILValue, 8> vjpDirectResults;
extractAllElements(vjpResult, getBuilder(), vjpDirectResults);
ArrayRef<SILValue> originalDirectResults =
ArrayRef<SILValue>(vjpDirectResults).drop_back(1);
SILValue originalDirectResult =
joinElements(originalDirectResults, getBuilder(), loc);
SILValue pullback = vjpDirectResults.back();
{
auto pullbackFnType = pullback->getType().castTo<SILFunctionType>();
auto pullbackUnsubstFnType =
pullbackFnType->getUnsubstitutedType(getModule());
if (pullbackFnType != pullbackUnsubstFnType) {
pullback = builder.createConvertFunction(
loc, pullback,
SILType::getPrimitiveObjectType(pullbackUnsubstFnType),
/*withoutActuallyEscaping*/ false);
}
}
// Store the original result to the value map.
mapValue(eai, originalDirectResult);
auto pullbackType = pullbackInfo.lookUpLinearMapType(bai);
// If actual pullback type does not match lowered pullback type, reabstract
// the pullback using a thunk.
auto actualPullbackType =
getOpType(pullback->getType()).getAs<SILFunctionType>();
auto loweredPullbackType =
getOpType(getLoweredType(pullbackType)).castTo<SILFunctionType>();
auto applyInfoIt = context.getNestedApplyInfo().find(bai);
assert(applyInfoIt != context.getNestedApplyInfo().end());
if (!loweredPullbackType->isEqual(actualPullbackType)) {
// Set non-reabstracted original pullback type in nested apply info.
applyInfoIt->second.originalPullbackType = actualPullbackType;
SILOptFunctionBuilder fb(context.getTransform());
pullback = reabstractCoroutine(
getBuilder(), fb, loc, pullback, loweredPullbackType,
[this](SubstitutionMap subs) -> SubstitutionMap {
return this->getOpSubstitutionMap(subs);
});
}
unsigned pullbackIdx = applyInfoIt->second.pullbackIdx;
pullbackValues[bai->getParent()][pullbackIdx] = pullback;
// Some instructions that produce the callee may have been cloned.
// If the original callee did not have any users beyond this `apply`,
// recursively kill the cloned callee.
if (auto *origCallee = cast_or_null<SingleValueInstruction>(
bai->getCallee()->getDefiningInstruction()))
if (origCallee->hasOneUse())
recursivelyDeleteTriviallyDeadInstructions(
getOpValue(origCallee)->getDefiningInstruction());
}
// Check and diagnose non-differentiable original function type.
bool diagnoseNondifferentiableOriginalFunctionType(CanSILFunctionType originalFnTy,
FullApplySite fai, SILValue origCallee,
const AutoDiffConfig &config) const {
// Check and diagnose non-differentiable arguments.
for (auto paramIndex : config.parameterIndices->getIndices()) {
if (!originalFnTy->getParameters()[paramIndex]
.getSILStorageInterfaceType()
.isDifferentiable(getModule())) {
auto arg = fai.getArgumentsWithoutIndirectResults()[paramIndex];
// FIXME: This shouldn't be necessary and might indicate a bug in
// the transformation.
RegularLocation nonAutoGenLoc(arg.getLoc());
nonAutoGenLoc.markNonAutoGenerated();
auto startLoc = nonAutoGenLoc.getStartSourceLoc();
auto endLoc = nonAutoGenLoc.getEndSourceLoc();
context.emitNondifferentiabilityError(
arg, invoker, diag::autodiff_nondifferentiable_argument)
.fixItInsert(startLoc, "withoutDerivative(at: ")
.fixItInsertAfter(endLoc, ")");
return true;
}
}
// Check and diagnose non-differentiable results.
unsigned firstSemanticParamResultIdx = originalFnTy->getNumResults();
unsigned firstYieldResultIndex = originalFnTy->getNumResults() +
originalFnTy->getNumAutoDiffSemanticResultsParameters();
for (auto resultIndex : config.resultIndices->getIndices()) {
SILType remappedResultType;
if (resultIndex >= firstYieldResultIndex) {
auto yieldResultIdx = resultIndex - firstYieldResultIndex;
const auto& yield = originalFnTy->getYields()[yieldResultIdx];
// We do not have a good way to differentiate direct yields
if (yield.isAutoDiffSemanticResult())
remappedResultType = yield.getSILStorageInterfaceType();
else {
context.emitNondifferentiabilityError(
origCallee, invoker,
diag::autodiff_cannot_differentiate_through_direct_yield);
return true;
}
} else if (resultIndex >= firstSemanticParamResultIdx) {
auto semanticResultArgIdx = resultIndex - firstSemanticParamResultIdx;
auto semanticResultArg =
*std::next(fai.getAutoDiffSemanticResultArguments().begin(),
semanticResultArgIdx);
remappedResultType = semanticResultArg->getType();
} else {
remappedResultType = originalFnTy->getResults()[resultIndex]
.getSILStorageInterfaceType();
}
if (!remappedResultType || !remappedResultType.isDifferentiable(getModule())) {
auto startLoc = fai.getLoc().getStartSourceLoc();
auto endLoc = fai.getLoc().getEndSourceLoc();
context.emitNondifferentiabilityError(
origCallee, invoker,
diag::autodiff_nondifferentiable_result)
.fixItInsert(startLoc, "withoutDerivative(at: ")
.fixItInsertAfter(endLoc, ")");
return true;
}
}
return false;
}
void visitBeginApplyInst(BeginApplyInst *bai) {
// If callee should not be differentiated, do standard cloning.
if (!pullbackInfo.shouldDifferentiateApplySite(bai)) {
LLVM_DEBUG(getADDebugStream() << "No active results:\n" << *bai << '\n');
TypeSubstCloner::visitBeginApplyInst(bai);
return;
}
Builder.setCurrentDebugScope(getOpScope(bai->getDebugScope()));
auto loc = bai->getLoc();
auto &builder = getBuilder();
auto origCallee = getOpValue(bai->getCallee());
auto originalFnTy = origCallee->getType().castTo<SILFunctionType>();
LLVM_DEBUG(getADDebugStream() << "VJP-transforming:\n" << *bai << '\n');
SmallVector<SILValue, 4> allResults;
SmallVector<unsigned, 8> activeParamIndices;
SmallVector<unsigned, 8> activeResultIndices;
collectMinimalIndicesForFunctionCall(bai, getConfig(), activityInfo,
allResults, activeParamIndices,
activeResultIndices);
assert(!activeParamIndices.empty() && "Parameter indices cannot be empty");
assert(!activeResultIndices.empty() && "Result indices cannot be empty");
LLVM_DEBUG(auto &s = getADDebugStream() << "Active indices: params=(";
llvm::interleave(
activeParamIndices.begin(), activeParamIndices.end(),
[&s](unsigned i) { s << i; }, [&s] { s << ", "; });
s << "), results=("; llvm::interleave(
activeResultIndices.begin(), activeResultIndices.end(),
[&s](unsigned i) { s << i; }, [&s] { s << ", "; });
s << ")\n";);
// Form expected indices.
AutoDiffConfig config(
IndexSubset::get(getASTContext(),
bai->getArgumentsWithoutIndirectResults().size(),
activeParamIndices),
IndexSubset::get(getASTContext(),
bai->getSubstCalleeType()->getNumAutoDiffSemanticResults(),
activeResultIndices));
if (diagnoseNondifferentiableOriginalFunctionType(originalFnTy,
bai, origCallee, config)) {
errorOccurred = true;
return;
}
// Emit the VJP.
SILValue vjpValue;
// If the original `apply` instruction has a substitution map, then the
// applied function is specialized.
// In the VJP, specialization is also necessary for parity. The original
// function operand is specialized with a remapped version of same
// substitution map using an argument-less `partial_apply`.
if (bai->getSubstitutionMap().empty()) {
origCallee = builder.emitCopyValueOperation(loc, origCallee);
} else {
auto substMap = getOpSubstitutionMap(bai->getSubstitutionMap());
auto vjpPartialApply = getBuilder().createPartialApply(
bai->getLoc(), origCallee, substMap, {},
ParameterConvention::Direct_Guaranteed);
origCallee = vjpPartialApply;
originalFnTy = origCallee->getType().castTo<SILFunctionType>();
// Diagnose if new original function type is non-differentiable.
if (diagnoseNondifferentiableOriginalFunctionType(originalFnTy,
bai, origCallee, config)) {
errorOccurred = true;
return;
}
}
auto *diffFuncInst =
context.createDifferentiableFunction(getBuilder(), loc,
config.parameterIndices, config.resultIndices,
origCallee);
// Record the `differentiable_function` instruction.
context.getDifferentiableFunctionInstWorklist().push_back(diffFuncInst);
builder.emitScopedBorrowOperation(
loc, diffFuncInst,
[&](SILValue borrowedADFunc) {
auto extractedVJP =
getBuilder().createDifferentiableFunctionExtract(
loc, NormalDifferentiableFunctionTypeComponent::VJP,
borrowedADFunc);
vjpValue = builder.emitCopyValueOperation(loc, extractedVJP);
});
builder.emitDestroyValueOperation(loc, diffFuncInst);
// Record desired/actual VJP indices.
// Temporarily set original pullback type to `None`.
NestedApplyInfo info{config, /*originalPullbackType*/ std::nullopt};
auto insertion = context.getNestedApplyInfo().try_emplace(bai, info);
auto &nestedApplyInfo = insertion.first->getSecond();
nestedApplyInfo = info;
// Call the VJP using the original parameters.
SmallVector<SILValue, 8> vjpArgs;
auto vjpFnTy = getOpType(vjpValue->getType()).castTo<SILFunctionType>();
auto numVJPArgs =
vjpFnTy->getNumParameters() + vjpFnTy->getNumIndirectFormalResults();
vjpArgs.reserve(numVJPArgs);
// Collect substituted arguments.
for (auto origArg : bai->getArguments())
vjpArgs.push_back(getOpValue(origArg));
// Apply the VJP.
// The VJP should be specialized, so no substitution map is necessary.
auto *vjpCall = getBuilder().createBeginApply(loc, vjpValue, SubstitutionMap(),
vjpArgs, bai->getApplyOptions());
LLVM_DEBUG(getADDebugStream() << "Applied vjp function\n" << *vjpCall);
// Note that vjpValue is destroyed after end_apply
// Store all the results (yields and token) to the value map.
assert(bai->getNumResults() == vjpCall->getNumResults());
for (unsigned i = 0; i < vjpCall->getNumResults(); ++i)
mapValue(bai->getResult(i), vjpCall->getResult(i));
// Checkpoint the pullback.
nestedApplyInfo.pullbackIdx = pullbackValues[bai->getParent()].size();
pullbackValues[bai->getParent()].push_back(SILValue());
// The rest of the cloning magic happens during `end_apply` cloning.
}
// If an `apply` has active results or active inout arguments, replace it
// with an `apply` of its VJP.
void visitApplyInst(ApplyInst *ai) {
// If callee should not be differentiated, do standard cloning.
if (!pullbackInfo.shouldDifferentiateApplySite(ai)) {
LLVM_DEBUG(getADDebugStream() << "No active results:\n" << *ai << '\n');
TypeSubstCloner::visitApplyInst(ai);
return;
}
// If callee is `array.uninitialized_intrinsic`, do standard cloning.
// `array.uninitialized_intrinsic` differentiation is handled separately.
if (ArraySemanticsCall(ai, semantics::ARRAY_UNINITIALIZED_INTRINSIC)) {
LLVM_DEBUG(getADDebugStream()
<< "Cloning `array.uninitialized_intrinsic` `apply`:\n"
<< *ai << '\n');
TypeSubstCloner::visitApplyInst(ai);
return;
}
// If callee is `array.finalize_intrinsic`, do standard cloning.
// `array.finalize_intrinsic` has special-case pullback generation.
if (ArraySemanticsCall(ai, semantics::ARRAY_FINALIZE_INTRINSIC)) {
LLVM_DEBUG(getADDebugStream()
<< "Cloning `array.finalize_intrinsic` `apply`:\n"
<< *ai << '\n');
TypeSubstCloner::visitApplyInst(ai);
return;
}
// If the original function is a semantic member accessor, do standard
// cloning. Semantic member accessors have special pullback generation
// logic, so all `apply` instructions can be directly cloned to the VJP.
if (isSemanticMemberAccessor(original)) {
LLVM_DEBUG(getADDebugStream()
<< "Cloning `apply` in semantic member accessor:\n"
<< *ai << '\n');
TypeSubstCloner::visitApplyInst(ai);
return;
}
Builder.setCurrentDebugScope(getOpScope(ai->getDebugScope()));
auto loc = ai->getLoc();
auto &builder = getBuilder();
auto origCallee = getOpValue(ai->getCallee());
auto originalFnTy = origCallee->getType().castTo<SILFunctionType>();
LLVM_DEBUG(getADDebugStream() << "VJP-transforming:\n" << *ai << '\n');
// Get the minimal parameter and result indices required for differentiating
// this `apply`.
SmallVector<SILValue, 4> allResults;
SmallVector<unsigned, 8> activeParamIndices;
SmallVector<unsigned, 8> activeResultIndices;
collectMinimalIndicesForFunctionCall(ai, getConfig(), activityInfo,
allResults, activeParamIndices,
activeResultIndices);
assert(!activeParamIndices.empty() && "Parameter indices cannot be empty");
assert(!activeResultIndices.empty() && "Result indices cannot be empty");
LLVM_DEBUG(auto &s = getADDebugStream() << "Active indices: params=(";
llvm::interleave(
activeParamIndices.begin(), activeParamIndices.end(),
[&s](unsigned i) { s << i; }, [&s] { s << ", "; });
s << "), results=("; llvm::interleave(
activeResultIndices.begin(), activeResultIndices.end(),
[&s](unsigned i) { s << i; }, [&s] { s << ", "; });
s << ")\n";);
// Form expected indices.
AutoDiffConfig config(
IndexSubset::get(getASTContext(),
ai->getArgumentsWithoutIndirectResults().size(),
activeParamIndices),
IndexSubset::get(getASTContext(),
ai->getSubstCalleeType()->getNumAutoDiffSemanticResults(),
activeResultIndices));
// Emit the VJP.
SILValue vjpValue;
// If functionSource is a `@differentiable` function, just extract it.
if (originalFnTy->isDifferentiable()) {
auto paramIndices = originalFnTy->getDifferentiabilityParameterIndices();
for (auto i : config.parameterIndices->getIndices()) {
if (!paramIndices->contains(i)) {
context.emitNondifferentiabilityError(
origCallee, invoker,
diag::
autodiff_function_noderivative_parameter_not_differentiable);
errorOccurred = true;
return;
}
}
builder.emitScopedBorrowOperation(
loc, origCallee, [&](SILValue borrowedDiffFunc) {
auto origFnType = origCallee->getType().castTo<SILFunctionType>();
auto origFnUnsubstType =
origFnType->getUnsubstitutedType(getModule());
if (origFnType != origFnUnsubstType) {
borrowedDiffFunc = builder.createConvertFunction(
loc, borrowedDiffFunc,
SILType::getPrimitiveObjectType(origFnUnsubstType),
/*withoutActuallyEscaping*/ false);
}
vjpValue = builder.createDifferentiableFunctionExtract(
loc, NormalDifferentiableFunctionTypeComponent::VJP,
borrowedDiffFunc);
vjpValue = builder.emitCopyValueOperation(loc, vjpValue);
});
auto vjpFnType = vjpValue->getType().castTo<SILFunctionType>();
auto vjpFnUnsubstType = vjpFnType->getUnsubstitutedType(getModule());
if (vjpFnType != vjpFnUnsubstType) {
vjpValue = builder.createConvertFunction(
loc, vjpValue, SILType::getPrimitiveObjectType(vjpFnUnsubstType),
/*withoutActuallyEscaping*/ false);
}
}
if (diagnoseNondifferentiableOriginalFunctionType(originalFnTy,
ai, origCallee, config)) {
errorOccurred = true;
return;
}
// If VJP has not yet been found, emit an `differentiable_function`
// instruction on the remapped original function operand and
// an `differentiable_function_extract` instruction to get the VJP.
// The `differentiable_function` instruction will be canonicalized during
// the transform main loop.
if (!vjpValue) {
// FIXME: Handle indirect differentiation invokers. This may require some
// redesign: currently, each original function + witness pair is mapped
// only to one invoker.
/*
DifferentiationInvoker indirect(ai, attr);
auto insertion =
context.getInvokers().try_emplace({original, attr}, indirect);
auto &invoker = insertion.first->getSecond();
invoker = indirect;
*/
// If the original `apply` instruction has a substitution map, then the
// applied function is specialized.
// In the VJP, specialization is also necessary for parity. The original
// function operand is specialized with a remapped version of same
// substitution map using an argument-less `partial_apply`.
if (ai->getSubstitutionMap().empty()) {
origCallee = builder.emitCopyValueOperation(loc, origCallee);
} else {
auto substMap = getOpSubstitutionMap(ai->getSubstitutionMap());
auto vjpPartialApply = getBuilder().createPartialApply(
ai->getLoc(), origCallee, substMap, {},
ParameterConvention::Direct_Guaranteed);
origCallee = vjpPartialApply;
originalFnTy = origCallee->getType().castTo<SILFunctionType>();
// Diagnose if new original function type is non-differentiable.
if (diagnoseNondifferentiableOriginalFunctionType(originalFnTy,
ai, origCallee, config)) {
errorOccurred = true;
return;
}
}
auto *diffFuncInst = context.createDifferentiableFunction(
getBuilder(), loc, config.parameterIndices, config.resultIndices,
origCallee);
// Record the `differentiable_function` instruction.
context.getDifferentiableFunctionInstWorklist().push_back(diffFuncInst);
builder.emitScopedBorrowOperation(
loc, diffFuncInst, [&](SILValue borrowedADFunc) {
auto extractedVJP =
getBuilder().createDifferentiableFunctionExtract(
loc, NormalDifferentiableFunctionTypeComponent::VJP,
borrowedADFunc);
vjpValue = builder.emitCopyValueOperation(loc, extractedVJP);
});
builder.emitDestroyValueOperation(loc, diffFuncInst);
}
// Record desired/actual VJP indices.
// Temporarily set original pullback type to `None`.
NestedApplyInfo info{config, /*originalPullbackType*/ std::nullopt};
auto insertion = context.getNestedApplyInfo().try_emplace(ai, info);
auto &nestedApplyInfo = insertion.first->getSecond();
nestedApplyInfo = info;
// Call the VJP using the original parameters.
SmallVector<SILValue, 8> vjpArgs;
auto vjpFnTy = getOpType(vjpValue->getType()).castTo<SILFunctionType>();
auto numVJPArgs =
vjpFnTy->getNumParameters() + vjpFnTy->getNumIndirectFormalResults();
vjpArgs.reserve(numVJPArgs);
// Collect substituted arguments.
for (auto origArg : ai->getArguments())
vjpArgs.push_back(getOpValue(origArg));
assert(vjpArgs.size() == numVJPArgs);
// Apply the VJP.
// The VJP should be specialized, so no substitution map is necessary.
auto *vjpCall = getBuilder().createApply(loc, vjpValue, SubstitutionMap(),
vjpArgs, ai->getApplyOptions());
LLVM_DEBUG(getADDebugStream() << "Applied vjp function\n" << *vjpCall);
builder.emitDestroyValueOperation(loc, vjpValue);
// Get the VJP results (original results and pullback).
SmallVector<SILValue, 8> vjpDirectResults;
extractAllElements(vjpCall, getBuilder(), vjpDirectResults);
ArrayRef<SILValue> originalDirectResults =
ArrayRef<SILValue>(vjpDirectResults).drop_back(1);
SILValue originalDirectResult =
joinElements(originalDirectResults, getBuilder(), vjpCall->getLoc());
SILValue pullback = vjpDirectResults.back();
{
auto pullbackFnType = pullback->getType().castTo<SILFunctionType>();
auto pullbackUnsubstFnType =
pullbackFnType->getUnsubstitutedType(getModule());
if (pullbackFnType != pullbackUnsubstFnType) {
pullback = builder.createConvertFunction(
loc, pullback,
SILType::getPrimitiveObjectType(pullbackUnsubstFnType),
/*withoutActuallyEscaping*/ false);
}
}
// Store the original result to the value map.
mapValue(ai, originalDirectResult);
// Checkpoint the pullback.
auto pullbackType = pullbackInfo.lookUpLinearMapType(ai);
// If actual pullback type does not match lowered pullback type, reabstract
// the pullback using a thunk.
auto actualPullbackType =
getOpType(pullback->getType()).getAs<SILFunctionType>();
auto loweredPullbackType =
getOpType(getLoweredType(pullbackType)).castTo<SILFunctionType>();
if (!loweredPullbackType->isEqual(actualPullbackType)) {
// Set non-reabstracted original pullback type in nested apply info.
nestedApplyInfo.originalPullbackType = actualPullbackType;
SILOptFunctionBuilder fb(context.getTransform());
pullback = reabstractFunction(
getBuilder(), fb, ai->getLoc(), pullback, loweredPullbackType,
[this](SubstitutionMap subs) -> SubstitutionMap {
return this->getOpSubstitutionMap(subs);
});
}
nestedApplyInfo.pullbackIdx = pullbackValues[ai->getParent()].size();
pullbackValues[ai->getParent()].push_back(pullback);
// Some instructions that produce the callee may have been cloned.
// If the original callee did not have any users beyond this `apply`,
// recursively kill the cloned callee.
if (auto *origCallee = cast_or_null<SingleValueInstruction>(
ai->getCallee()->getDefiningInstruction()))
if (origCallee->hasOneUse())
recursivelyDeleteTriviallyDeadInstructions(
getOpValue(origCallee)->getDefiningInstruction());
}
void visitTryApplyInst(TryApplyInst *tai) {
Builder.setCurrentDebugScope(getOpScope(tai->getDebugScope()));
// Build pullback struct value for original block.
auto *pbTupleVal = buildPullbackValueTupleValue(tai);
// Create a new `try_apply` instruction.
auto args = getOpValueArray<8>(tai->getArguments());
getBuilder().createTryApply(
tai->getLoc(), getOpValue(tai->getCallee()),
getOpSubstitutionMap(tai->getSubstitutionMap()), args,
createTrampolineBasicBlock(tai, pbTupleVal, tai->getNormalBB()),
createTrampolineBasicBlock(tai, pbTupleVal, tai->getErrorBB()),
tai->getApplyOptions());
}