-
Notifications
You must be signed in to change notification settings - Fork 125
/
Copy pathReverseModeVisitor.cpp
3093 lines (2811 loc) · 127 KB
/
ReverseModeVisitor.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
//--------------------------------------------------------------------*- C++ -*-
// clad - the C++ Clang-based Automatic Differentiator
// version: $Id: ClangPlugin.cpp 7 2013-06-01 22:48:03Z [email protected] $
// author: Vassil Vassilev <vvasilev-at-cern.ch>
//------------------------------------------------------------------------------
#include "clad/Differentiator/ReverseModeVisitor.h"
#include "ConstantFolder.h"
#include "clad/Differentiator/DiffPlanner.h"
#include "clad/Differentiator/ErrorEstimator.h"
#include "clad/Differentiator/StmtClone.h"
#include "clad/Differentiator/ExternalRMVSource.h"
#include "clad/Differentiator/MultiplexExternalRMVSource.h"
#include "clang/AST/ASTContext.h"
#include "clang/AST/Expr.h"
#include "clang/AST/TemplateBase.h"
#include "clang/Sema/Lookup.h"
#include "clang/Sema/Overload.h"
#include "clang/Sema/Scope.h"
#include "clang/Sema/Sema.h"
#include "clang/Sema/SemaInternal.h"
#include "clang/Sema/Template.h"
#include "llvm/Support/SaveAndRestore.h"
#include <algorithm>
#include <numeric>
#include "clad/Differentiator/CladUtils.h"
#include "clad/Differentiator/Compatibility.h"
using namespace clang;
namespace clad {
Expr* ReverseModeVisitor::CladTapeResult::Last() {
LookupResult& Back = V.GetCladTapeBack();
CXXScopeSpec CSS;
CSS.Extend(V.m_Context, V.GetCladNamespace(), noLoc, noLoc);
Expr* BackDRE = V.m_Sema
.BuildDeclarationNameExpr(CSS, Back,
/*AcceptInvalidDecl=*/false)
.get();
Expr* Call =
V.m_Sema.ActOnCallExpr(V.getCurrentScope(), BackDRE, noLoc, Ref, noLoc)
.get();
return Call;
}
ReverseModeVisitor::CladTapeResult
ReverseModeVisitor::MakeCladTapeFor(Expr* E, llvm::StringRef prefix) {
assert(E && "must be provided");
QualType TapeType =
GetCladTapeOfType(getNonConstType(E->getType(), m_Context, m_Sema));
LookupResult& Push = GetCladTapePush();
LookupResult& Pop = GetCladTapePop();
Expr* TapeRef =
BuildDeclRef(GlobalStoreImpl(TapeType, prefix, getZeroInit(TapeType)));
auto VD = cast<VarDecl>(cast<DeclRefExpr>(TapeRef)->getDecl());
// Add fake location, since Clang AST does assert(Loc.isValid()) somewhere.
VD->setLocation(m_Function->getLocation());
CXXScopeSpec CSS;
CSS.Extend(m_Context, GetCladNamespace(), noLoc, noLoc);
auto PopDRE = m_Sema
.BuildDeclarationNameExpr(CSS, Pop,
/*AcceptInvalidDecl=*/false)
.get();
auto PushDRE = m_Sema
.BuildDeclarationNameExpr(CSS, Push,
/*AcceptInvalidDecl=*/false)
.get();
Expr* PopExpr =
m_Sema.ActOnCallExpr(getCurrentScope(), PopDRE, noLoc, TapeRef, noLoc)
.get();
Expr* CallArgs[] = {TapeRef, E};
Expr* PushExpr =
m_Sema.ActOnCallExpr(getCurrentScope(), PushDRE, noLoc, CallArgs, noLoc)
.get();
return CladTapeResult{*this, PushExpr, PopExpr, TapeRef};
}
ReverseModeVisitor::ReverseModeVisitor(DerivativeBuilder& builder)
: VisitorBase(builder), m_Result(nullptr) {}
ReverseModeVisitor::~ReverseModeVisitor() {
if (m_ExternalSource) {
// Inform external sources that `ReverseModeVisitor` object no longer
// exists.
// FIXME: Make this so the lifetime scope of the source matches.
// m_ExternalSource->ForgetRMV();
// Free the external sources multiplexer since we own this resource.
delete m_ExternalSource;
}
}
FunctionDecl* ReverseModeVisitor::CreateGradientOverload() {
auto gradientParams = m_Derivative->parameters();
auto gradientNameInfo = m_Derivative->getNameInfo();
bool isStaticMethod = utils::IsStaticMethod(m_Function);
// Calculate the total number of parameters that would be required for
// automatic differentiation in the derived function if all args are
// requested.
// FIXME: Here we are assuming all function parameters are of differentiable
// type. Ideally, we should not make any such assumption.
std::size_t totalDerivedParamsSize = m_Function->getNumParams() * 2;
std::size_t numOfDerivativeParams =
m_Function->getNumParams() + !isStaticMethod;
// All output parameters will be of type `clad::array_ref<void>`. These
// parameters will be casted to correct type before the call to the actual
// derived function.
// We require each output parameter to be of same type in the overloaded
// derived function due to limitations of generating the exact derived
// function type at the compile-time (without clad plugin help).
QualType outputParamType = GetCladArrayRefOfType(m_Context.VoidTy);
llvm::SmallVector<QualType, 16> paramTypes;
// Add types for representing original function parameters.
for (auto PVD : m_Function->parameters())
paramTypes.push_back(PVD->getType());
// Add types for representing parameter derivatives.
// FIXME: We are assuming all function parameters are differentiable. We
// should not make any such assumptions.
for (std::size_t i = 0; i < numOfDerivativeParams; ++i)
paramTypes.push_back(outputParamType);
auto gradFuncOverloadEPI =
dyn_cast<FunctionProtoType>(m_Function->getType())->getExtProtoInfo();
QualType gradientFunctionOverloadType =
m_Context.getFunctionType(m_Context.VoidTy, paramTypes,
// Cast to function pointer.
gradFuncOverloadEPI);
DeclContext* DC = const_cast<DeclContext*>(m_Function->getDeclContext());
m_Sema.CurContext = DC;
DeclWithContext gradientOverloadFDWC =
m_Builder.cloneFunction(m_Function, *this, DC, m_Sema, m_Context, noLoc,
gradientNameInfo, gradientFunctionOverloadType);
FunctionDecl* gradientOverloadFD = gradientOverloadFDWC.first;
beginScope(Scope::FunctionPrototypeScope | Scope::FunctionDeclarationScope |
Scope::DeclScope);
m_Sema.PushFunctionScope();
m_Sema.PushDeclContext(getCurrentScope(), gradientOverloadFD);
llvm::SmallVector<ParmVarDecl*, 4> overloadParams;
llvm::SmallVector<Expr*, 4> callArgs;
overloadParams.reserve(totalDerivedParamsSize);
callArgs.reserve(gradientParams.size());
for (auto PVD : m_Function->parameters()) {
auto VD = utils::BuildParmVarDecl(
m_Sema, gradientOverloadFD, PVD->getIdentifier(), PVD->getType(),
PVD->getStorageClass(), /*defArg=*/nullptr, PVD->getTypeSourceInfo());
overloadParams.push_back(VD);
callArgs.push_back(BuildDeclRef(VD));
}
for (std::size_t i = 0; i < numOfDerivativeParams; ++i) {
IdentifierInfo* II = nullptr;
StorageClass SC = StorageClass::SC_None;
std::size_t effectiveGradientIndex = m_Function->getNumParams() + i;
// `effectiveGradientIndex < gradientParams.size()` implies that this
// parameter represents an actual derivative of one of the function
// original parameters.
if (effectiveGradientIndex < gradientParams.size()) {
auto GVD = gradientParams[effectiveGradientIndex];
II = CreateUniqueIdentifier("_temp_" + GVD->getNameAsString());
SC = GVD->getStorageClass();
} else {
II = CreateUniqueIdentifier("_d_" + std::to_string(i));
}
auto PVD = utils::BuildParmVarDecl(m_Sema, gradientOverloadFD, II,
outputParamType, SC);
overloadParams.push_back(PVD);
}
for (auto PVD : overloadParams) {
if (PVD->getIdentifier())
m_Sema.PushOnScopeChains(PVD, getCurrentScope(),
/*AddToContext=*/false);
}
gradientOverloadFD->setParams(overloadParams);
gradientOverloadFD->setBody(/*B=*/nullptr);
beginScope(Scope::FnScope | Scope::DeclScope);
m_DerivativeFnScope = getCurrentScope();
beginBlock();
// Build derivatives to be used in the call to the actual derived function.
// These are initialised by effectively casting the derivative parameters of
// overloaded derived function to the correct type.
for (std::size_t i = m_Function->getNumParams(); i < gradientParams.size();
++i) {
auto overloadParam = overloadParams[i];
auto gradientParam = gradientParams[i];
auto gradientVD =
BuildVarDecl(gradientParam->getType(), gradientParam->getName(),
BuildDeclRef(overloadParam));
callArgs.push_back(BuildDeclRef(gradientVD));
addToCurrentBlock(BuildDeclStmt(gradientVD));
}
Expr* callExpr = BuildCallExprToFunction(m_Derivative, callArgs,
/*UseRefQualifiedThisObj=*/true);
addToCurrentBlock(callExpr);
Stmt* gradientOverloadBody = endBlock();
gradientOverloadFD->setBody(gradientOverloadBody);
endScope(); // Function body scope
m_Sema.PopFunctionScopeInfo();
m_Sema.PopDeclContext();
endScope(); // Function decl scope
return gradientOverloadFD;
}
DerivativeAndOverload
ReverseModeVisitor::Derive(const FunctionDecl* FD,
const DiffRequest& request) {
if (m_ExternalSource)
m_ExternalSource->ActOnStartOfDerive();
silenceDiags = !request.VerboseDiags;
m_Function = FD;
// reverse mode plugins may have request mode other than
// `DiffMode::reverse`, but they still need the `DiffMode::reverse` mode
// specific behaviour, because they are "reverse" mode plugins.
m_Mode = DiffMode::reverse;
if (request.Mode == DiffMode::jacobian)
m_Mode = DiffMode::jacobian;
m_Pullback =
ConstantFolder::synthesizeLiteral(m_Context.IntTy, m_Context, 1);
assert(m_Function && "Must not be null.");
DiffParams args{};
DiffInputVarsInfo DVI;
if (request.Args) {
DVI = request.DVI;
for (auto dParam : DVI)
args.push_back(dParam.param);
}
else
std::copy(FD->param_begin(), FD->param_end(), std::back_inserter(args));
if (args.empty())
return {};
if (m_ExternalSource)
m_ExternalSource->ActAfterParsingDiffArgs(request, args);
// Save the type of the output parameter(s) that is add by clad to the
// derived function
if (request.Mode == DiffMode::jacobian) {
isVectorValued = true;
unsigned lastArgN = m_Function->getNumParams() - 1;
outputArrayStr = m_Function->getParamDecl(lastArgN)->getNameAsString();
}
// Check if DiffRequest asks for use of enzyme as backend
if (request.use_enzyme)
use_enzyme = true;
auto derivativeBaseName = request.BaseFunctionName;
std::string gradientName = derivativeBaseName + funcPostfix();
// To be consistent with older tests, nothing is appended to 'f_grad' if
// we differentiate w.r.t. all the parameters at once.
if(isVectorValued){
// If Jacobian is asked, the last parameter is the result parameter
// and should be ignored
if (args.size() != FD->getNumParams()-1){
for (auto arg : args) {
auto it = std::find(FD->param_begin(), FD->param_end()-1, arg);
auto idx = std::distance(FD->param_begin(), it);
gradientName += ('_' + std::to_string(idx));
}
}
}else{
if (args.size() != FD->getNumParams()){
for (auto arg : args) {
auto it = std::find(FD->param_begin(), FD->param_end(), arg);
auto idx = std::distance(FD->param_begin(), it);
gradientName += ('_' + std::to_string(idx));
}
}
}
IdentifierInfo* II = &m_Context.Idents.get(gradientName);
DeclarationNameInfo name(II, noLoc);
// If we are in error estimation mode, we have an extra `double&`
// parameter that stores the final error
unsigned numExtraParam = 0;
if (m_ExternalSource)
m_ExternalSource->ActBeforeCreatingDerivedFnParamTypes(numExtraParam);
auto paramTypes = ComputeParamTypes(args);
if (m_ExternalSource)
m_ExternalSource->ActAfterCreatingDerivedFnParamTypes(paramTypes);
// If reverse mode differentiates only part of the arguments it needs to
// generate an overload that can take in all the diff variables
bool shouldCreateOverload = false;
// FIXME: Gradient overload doesn't know how to handle additional parameters
// added by the plugins yet.
if (!isVectorValued && numExtraParam == 0)
shouldCreateOverload = true;
auto originalFnType = dyn_cast<FunctionProtoType>(m_Function->getType());
// For a function f of type R(A1, A2, ..., An),
// the type of the gradient function is void(A1, A2, ..., An, R*, R*, ...,
// R*) . the type of the jacobian function is void(A1, A2, ..., An, R*, R*)
// and for error estimation, the function type is
// void(A1, A2, ..., An, R*, R*, ..., R*, double&)
QualType gradientFunctionType = m_Context.getFunctionType(
m_Context.VoidTy,
llvm::ArrayRef<QualType>(paramTypes.data(), paramTypes.size()),
// Cast to function pointer.
originalFnType->getExtProtoInfo());
// Create the gradient function declaration.
llvm::SaveAndRestore<DeclContext*> SaveContext(m_Sema.CurContext);
llvm::SaveAndRestore<Scope*> SaveScope(m_CurScope);
DeclContext* DC = const_cast<DeclContext*>(m_Function->getDeclContext());
m_Sema.CurContext = DC;
DeclWithContext result = m_Builder.cloneFunction(m_Function,
*this,
DC,
m_Sema,
m_Context,
noLoc,
name,
gradientFunctionType);
FunctionDecl* gradientFD = result.first;
m_Derivative = gradientFD;
if (m_ExternalSource)
m_ExternalSource->ActBeforeCreatingDerivedFnScope();
// Function declaration scope
beginScope(Scope::FunctionPrototypeScope | Scope::FunctionDeclarationScope |
Scope::DeclScope);
m_Sema.PushFunctionScope();
m_Sema.PushDeclContext(getCurrentScope(), m_Derivative);
if (m_ExternalSource)
m_ExternalSource->ActAfterCreatingDerivedFnScope();
auto params = BuildParams(args);
if (m_ExternalSource)
m_ExternalSource->ActAfterCreatingDerivedFnParams(params);
llvm::ArrayRef<ParmVarDecl*> paramsRef =
llvm::makeArrayRef(params.data(), params.size());
gradientFD->setParams(paramsRef);
gradientFD->setBody(nullptr);
if (isVectorValued) {
// Reference to the output parameter.
m_Result = BuildDeclRef(params.back());
numParams = args.size();
// Creates the ArraySubscriptExprs for the independent variables
size_t idx = 0;
for (auto arg : args) {
// FIXME: fix when adding array inputs, now we are just skipping all
// array/pointer inputs (not treating them as independent variables).
if (utils::isArrayOrPointerType(arg->getType())) {
if (arg->getName() == "p")
m_Variables[arg] = m_Result;
idx += 1;
continue;
}
auto size_type = m_Context.getSizeType();
unsigned size_type_bits = m_Context.getIntWidth(size_type);
// Create the idx literal.
auto i =
IntegerLiteral::Create(m_Context, llvm::APInt(size_type_bits, idx),
size_type, noLoc);
// Create the jacobianMatrix[idx] expression.
auto result_at_i =
m_Sema.CreateBuiltinArraySubscriptExpr(m_Result, noLoc, i, noLoc)
.get();
m_Variables[arg] = result_at_i;
idx += 1;
m_IndependentVars.push_back(arg);
}
}
if (m_ExternalSource)
m_ExternalSource->ActBeforeCreatingDerivedFnBodyScope();
// Function body scope.
beginScope(Scope::FnScope | Scope::DeclScope);
m_DerivativeFnScope = getCurrentScope();
beginBlock();
if (m_ExternalSource)
m_ExternalSource->ActOnStartOfDerivedFnBody(request);
Stmt* gradientBody = nullptr;
// create derived variables for parameters which are not part of
// independent variables (args).
if (!use_enzyme) {
for (std::size_t i = 0; i < m_Function->getNumParams(); ++i) {
ParmVarDecl* param = params[i];
// derived variables are already created for independent variables.
if (m_Variables.count(param))
continue;
// in vector mode last non diff parameter is output parameter.
if (isVectorValued && i == m_Function->getNumParams() - 1)
continue;
auto VDDerivedType = param->getType();
// We cannot initialize derived variable for pointer types because
// we do not know the correct size.
if (utils::isArrayOrPointerType(VDDerivedType))
continue;
auto VDDerived =
BuildVarDecl(VDDerivedType, "_d_" + param->getNameAsString(),
getZeroInit(VDDerivedType));
m_Variables[param] = BuildDeclRef(VDDerived);
addToBlock(BuildDeclStmt(VDDerived), m_Globals);
}
// Start the visitation process which outputs the statements in the
// current block.
StmtDiff BodyDiff = Visit(FD->getBody());
Stmt* Forward = BodyDiff.getStmt();
Stmt* Reverse = BodyDiff.getStmt_dx();
// Create the body of the function.
// Firstly, all "global" Stmts are put into fn's body.
for (Stmt* S : m_Globals)
addToCurrentBlock(S, direction::forward);
// Forward pass.
if (auto CS = dyn_cast<CompoundStmt>(Forward))
for (Stmt* S : CS->body())
addToCurrentBlock(S, direction::forward);
else
addToCurrentBlock(Forward, direction::forward);
// Reverse pass.
if (auto RCS = dyn_cast<CompoundStmt>(Reverse))
for (Stmt* S : RCS->body())
addToCurrentBlock(S, direction::forward);
else
addToCurrentBlock(Reverse, direction::forward);
if (m_ExternalSource)
m_ExternalSource->ActOnEndOfDerivedFnBody();
gradientBody = endBlock();
} else {
// TODO: Write code to generate code that enzyme can work on
/*
Two if cases ought to come here
a. How to deal with functions of form - double function(double z, double
y, double z...); This is not straight forward as of now because Enzyme
does not have support for this yet, we will need to setup data
structures that can deal with this easily
b. How to deal with functions of the form - double function(double*
arrayOfParams); This is straightforward to deal in enzyme
*/
gradientBody = endBlock();
}
m_Derivative->setBody(gradientBody);
endScope(); // Function body scope
m_Sema.PopFunctionScopeInfo();
m_Sema.PopDeclContext();
endScope(); // Function decl scope
FunctionDecl* gradientOverloadFD = nullptr;
if (shouldCreateOverload) {
gradientOverloadFD =
CreateGradientOverload();
}
return DerivativeAndOverload{result.first, gradientOverloadFD};
}
DerivativeAndOverload
ReverseModeVisitor::DerivePullback(const clang::FunctionDecl* FD,
const DiffRequest& request) {
// FIXME: Duplication of external source here is a workaround
// for the two 'Derive's being different functions.
if (m_ExternalSource)
m_ExternalSource->ActOnStartOfDerive();
silenceDiags = !request.VerboseDiags;
m_Function = FD;
m_Mode = DiffMode::experimental_pullback;
assert(m_Function && "Must not be null.");
DiffParams args{};
std::copy(FD->param_begin(), FD->param_end(), std::back_inserter(args));
bool isStaticMethod = utils::IsStaticMethod(FD);
assert((!args.empty() || !isStaticMethod) &&
"Cannot generate pullback function of a function "
"with no differentiable arguments");
if (m_ExternalSource)
m_ExternalSource->ActAfterParsingDiffArgs(request, args);
auto derivativeName = request.BaseFunctionName + "_pullback";
auto DNI = utils::BuildDeclarationNameInfo(m_Sema, derivativeName);
auto paramTypes = ComputeParamTypes(args);
auto originalFnType = dyn_cast<FunctionProtoType>(m_Function->getType());
if (m_ExternalSource)
m_ExternalSource->ActAfterCreatingDerivedFnParamTypes(paramTypes);
QualType pullbackFnType = m_Context.getFunctionType(
m_Context.VoidTy, paramTypes, originalFnType->getExtProtoInfo());
llvm::SaveAndRestore<DeclContext*> saveContext(m_Sema.CurContext);
llvm::SaveAndRestore<Scope*> saveScope(m_CurScope);
m_Sema.CurContext = const_cast<DeclContext*>(m_Function->getDeclContext());
DeclWithContext fnBuildRes =
m_Builder.cloneFunction(m_Function, *this, m_Sema.CurContext, m_Sema,
m_Context, noLoc, DNI, pullbackFnType);
m_Derivative = fnBuildRes.first;
if (m_ExternalSource)
m_ExternalSource->ActBeforeCreatingDerivedFnScope();
beginScope(Scope::FunctionPrototypeScope | Scope::FunctionDeclarationScope |
Scope::DeclScope);
m_Sema.PushFunctionScope();
m_Sema.PushDeclContext(getCurrentScope(), m_Derivative);
if (m_ExternalSource)
m_ExternalSource->ActAfterCreatingDerivedFnScope();
auto params = BuildParams(args);
if (m_ExternalSource)
m_ExternalSource->ActAfterCreatingDerivedFnParams(params);
m_Derivative->setParams(params);
m_Derivative->setBody(nullptr);
if (m_ExternalSource)
m_ExternalSource->ActBeforeCreatingDerivedFnBodyScope();
beginScope(Scope::FnScope | Scope::DeclScope);
m_DerivativeFnScope = getCurrentScope();
beginBlock();
if (m_ExternalSource)
m_ExternalSource->ActOnStartOfDerivedFnBody(request);
StmtDiff bodyDiff = Visit(m_Function->getBody());
Stmt* forward = bodyDiff.getStmt();
Stmt* reverse = bodyDiff.getStmt_dx();
// Create the body of the function.
// Firstly, all "global" Stmts are put into fn's body.
for (Stmt* S : m_Globals)
addToCurrentBlock(S, direction::forward);
// Forward pass.
if (auto CS = dyn_cast<CompoundStmt>(forward))
for (Stmt* S : CS->body())
addToCurrentBlock(S, direction::forward);
// Reverse pass.
if (auto RCS = dyn_cast<CompoundStmt>(reverse))
for (Stmt* S : RCS->body())
addToCurrentBlock(S, direction::forward);
if (m_ExternalSource)
m_ExternalSource->ActOnEndOfDerivedFnBody();
Stmt* fnBody = endBlock();
m_Derivative->setBody(fnBody);
endScope(); // Function body scope
m_Sema.PopFunctionScopeInfo();
m_Sema.PopDeclContext();
endScope(); // Function decl scope
return DerivativeAndOverload{fnBuildRes.first, nullptr};
}
StmtDiff ReverseModeVisitor::VisitStmt(const Stmt* S) {
diag(
DiagnosticsEngine::Warning,
S->getBeginLoc(),
"attempted to differentiate unsupported statement, no changes applied");
// Unknown stmt, just clone it.
return StmtDiff(Clone(S));
}
StmtDiff ReverseModeVisitor::VisitCompoundStmt(const CompoundStmt* CS) {
beginScope(Scope::DeclScope);
beginBlock(direction::forward);
beginBlock(direction::reverse);
for (Stmt* S : CS->body()) {
if (m_ExternalSource)
m_ExternalSource->ActBeforeDifferentiatingStmtInVisitCompoundStmt();
StmtDiff SDiff = DifferentiateSingleStmt(S);
addToCurrentBlock(SDiff.getStmt(), direction::forward);
addToCurrentBlock(SDiff.getStmt_dx(), direction::reverse);
if (m_ExternalSource)
m_ExternalSource->ActAfterProcessingStmtInVisitCompoundStmt();
}
CompoundStmt* Forward = endBlock(direction::forward);
CompoundStmt* Reverse = endBlock(direction::reverse);
endScope();
return StmtDiff(Forward, Reverse);
}
static Stmt* unwrapIfSingleStmt(Stmt* S) {
if (!S)
return nullptr;
if (!isa<CompoundStmt>(S))
return S;
auto CS = cast<CompoundStmt>(S);
if (CS->size() == 0)
return nullptr;
else if (CS->size() == 1)
return CS->body_front();
else
return CS;
}
StmtDiff ReverseModeVisitor::VisitIfStmt(const clang::IfStmt* If) {
// Control scope of the IfStmt. E.g., in if (double x = ...) {...}, x goes
// to this scope.
beginScope(Scope::DeclScope | Scope::ControlScope);
StmtDiff cond = Clone(If->getCond());
// Condition has to be stored as a "global" variable, to take the correct
// branch in the reverse pass.
// If we are inside loop, the condition has to be stored in a stack after
// the if statement.
Expr* PushCond = nullptr;
Expr* PopCond = nullptr;
auto condExpr = Visit(cond.getExpr());
if (isInsideLoop) {
// If we are inside for loop, cond will be stored in the following way:
// forward:
// _t = cond;
// if (_t) { ... }
// clad::push(..., _t);
// reverse:
// if (clad::pop(...)) { ... }
// Simply doing
// if (clad::push(..., _t) { ... }
// is incorrect when if contains return statement inside: return will
// skip corresponding push.
cond = StoreAndRef(condExpr.getExpr(), direction::forward, "_t",
/*forceDeclCreation=*/true);
StmtDiff condPushPop = GlobalStoreAndRef(cond.getExpr(), "_cond");
PushCond = condPushPop.getExpr();
PopCond = condPushPop.getExpr_dx();
} else
cond = GlobalStoreAndRef(condExpr.getExpr(), "_cond");
// Convert cond to boolean condition. We are modifying each Stmt in
// StmtDiff.
for (Stmt*& S : cond.getBothStmts())
if (S)
S = m_Sema
.ActOnCondition(m_CurScope,
noLoc,
cast<Expr>(S),
Sema::ConditionKind::Boolean)
.get()
.second;
// Create a block "around" if statement, e.g:
// {
// ...
// if (...) {...}
// }
beginBlock(direction::forward);
beginBlock(direction::reverse);
const Stmt* init = If->getInit();
StmtDiff initResult = init ? Visit(init) : StmtDiff{};
// If there is Init, it's derivative will be output in the block before if:
// E.g., for:
// if (int x = 1; ...) {...}
// result will be:
// {
// int _d_x = 0;
// if (int x = 1; ...) {...}
// }
// This is done to avoid variable names clashes.
addToCurrentBlock(initResult.getStmt_dx());
VarDecl* condVarClone = nullptr;
if (const VarDecl* condVarDecl = If->getConditionVariable()) {
VarDeclDiff condVarDeclDiff = DifferentiateVarDecl(condVarDecl);
condVarClone = condVarDeclDiff.getDecl();
if (condVarDeclDiff.getDecl_dx())
addToBlock(BuildDeclStmt(condVarDeclDiff.getDecl_dx()), m_Globals);
}
// Condition is just cloned as it is, not derived.
// FIXME: if condition changes one of the variables, it may be reasonable
// to derive it, e.g.
// if (x += x) {...}
// should result in:
// {
// _d_y += _d_x
// if (y += x) {...}
// }
auto VisitBranch = [&](const Stmt* Branch) -> StmtDiff {
if (!Branch)
return {};
if (isa<CompoundStmt>(Branch)) {
StmtDiff BranchDiff = Visit(Branch);
return BranchDiff;
} else {
beginBlock(direction::forward);
if (m_ExternalSource)
m_ExternalSource->ActBeforeDifferentiatingSingleStmtBranchInVisitIfStmt();
StmtDiff BranchDiff = DifferentiateSingleStmt(Branch, /*dfdS=*/nullptr);
addToCurrentBlock(BranchDiff.getStmt(), direction::forward);
if (m_ExternalSource)
m_ExternalSource->ActBeforeFinalisingVisitBranchSingleStmtInIfVisitStmt();
Stmt* Forward = unwrapIfSingleStmt(endBlock(direction::forward));
Stmt* Reverse = unwrapIfSingleStmt(BranchDiff.getStmt_dx());
return StmtDiff(Forward, Reverse);
}
};
StmtDiff thenDiff = VisitBranch(If->getThen());
StmtDiff elseDiff = VisitBranch(If->getElse());
// It is problematic to specify both condVarDecl and cond thorugh
// Sema::ActOnIfStmt, therefore we directly use the IfStmt constructor.
Stmt* Forward = clad_compat::IfStmt_Create(m_Context,
noLoc,
If->isConstexpr(),
initResult.getStmt(),
condVarClone,
cond.getExpr(),
noLoc,
noLoc,
thenDiff.getStmt(),
noLoc,
elseDiff.getStmt());
addToCurrentBlock(Forward, direction::forward);
Expr* reverseCond = cond.getExpr_dx();
if (isInsideLoop) {
addToCurrentBlock(PushCond, direction::forward);
reverseCond = PopCond;
}
Stmt* Reverse = clad_compat::IfStmt_Create(m_Context,
noLoc,
If->isConstexpr(),
initResult.getStmt_dx(),
condVarClone,
reverseCond,
noLoc,
noLoc,
thenDiff.getStmt_dx(),
noLoc,
elseDiff.getStmt_dx());
addToCurrentBlock(Reverse, direction::reverse);
CompoundStmt* ForwardBlock = endBlock(direction::forward);
CompoundStmt* ReverseBlock = endBlock(direction::reverse);
endScope();
return StmtDiff(unwrapIfSingleStmt(ForwardBlock),
unwrapIfSingleStmt(ReverseBlock));
}
StmtDiff ReverseModeVisitor::VisitConditionalOperator(
const clang::ConditionalOperator* CO) {
StmtDiff cond = Clone(CO->getCond());
// Condition has to be stored as a "global" variable, to take the correct
// branch in the reverse pass.
cond = GlobalStoreAndRef(Visit(cond.getExpr()).getExpr(), "_cond");
// Convert cond to boolean condition. We are modifying each Stmt in
// StmtDiff.
for (Stmt*& S : cond.getBothStmts())
S = m_Sema
.ActOnCondition(m_CurScope,
noLoc,
cast<Expr>(S),
Sema::ConditionKind::Boolean)
.get()
.second;
auto ifTrue = CO->getTrueExpr();
auto ifFalse = CO->getFalseExpr();
auto VisitBranch = [&](const Expr* Branch,
Expr* dfdx) -> std::pair<StmtDiff, StmtDiff> {
auto Result = DifferentiateSingleExpr(Branch, dfdx);
StmtDiff BranchDiff = Result.first;
StmtDiff ExprDiff = Result.second;
Stmt* Forward = unwrapIfSingleStmt(BranchDiff.getStmt());
Stmt* Reverse = unwrapIfSingleStmt(BranchDiff.getStmt_dx());
return {StmtDiff(Forward, Reverse), ExprDiff};
};
StmtDiff ifTrueDiff;
StmtDiff ifTrueExprDiff;
StmtDiff ifFalseDiff;
StmtDiff ifFalseExprDiff;
std::tie(ifTrueDiff, ifTrueExprDiff) = VisitBranch(ifTrue, dfdx());
std::tie(ifFalseDiff, ifFalseExprDiff) = VisitBranch(ifFalse, dfdx());
auto BuildIf = [&](Expr* Cond, Stmt* Then, Stmt* Else) -> Stmt* {
if (!Then && !Else)
return nullptr;
if (!Then)
Then = m_Sema.ActOnNullStmt(noLoc).get();
return clad_compat::IfStmt_Create(m_Context,
noLoc,
false,
nullptr,
nullptr,
Cond,
noLoc,
noLoc,
Then,
noLoc,
Else);
};
Stmt* Forward =
BuildIf(cond.getExpr(), ifTrueDiff.getStmt(), ifFalseDiff.getStmt());
Stmt* Reverse = BuildIf(cond.getExpr_dx(),
ifTrueDiff.getStmt_dx(),
ifFalseDiff.getStmt_dx());
if (Forward)
addToCurrentBlock(Forward, direction::forward);
if (Reverse)
addToCurrentBlock(Reverse, direction::reverse);
Expr* condExpr = m_Sema
.ActOnConditionalOp(noLoc,
noLoc,
cond.getExpr(),
ifTrueExprDiff.getExpr(),
ifFalseExprDiff.getExpr())
.get();
// If result is a glvalue, we should keep it as it can potentially be
// assigned as in (c ? a : b) = x;
if ((CO->isModifiableLvalue(m_Context) == Expr::MLV_Valid) &&
ifTrueExprDiff.getExpr_dx() && ifFalseExprDiff.getExpr_dx()) {
Expr* ResultRef = m_Sema
.ActOnConditionalOp(noLoc,
noLoc,
cond.getExpr_dx(),
ifTrueExprDiff.getExpr_dx(),
ifFalseExprDiff.getExpr_dx())
.get();
if (ResultRef->isModifiableLvalue(m_Context) != Expr::MLV_Valid)
ResultRef = nullptr;
return StmtDiff(condExpr, ResultRef);
}
return StmtDiff(condExpr);
}
StmtDiff ReverseModeVisitor::VisitForStmt(const ForStmt* FS) {
beginScope(Scope::DeclScope | Scope::ControlScope | Scope::BreakScope |
Scope::ContinueScope);
LoopCounter loopCounter(*this);
if (loopCounter.getPush())
addToCurrentBlock(loopCounter.getPush());
beginBlock(direction::forward);
beginBlock(direction::reverse);
const Stmt* init = FS->getInit();
if (m_ExternalSource)
m_ExternalSource->ActBeforeDifferentiatingLoopInitStmt();
StmtDiff initResult = init ? DifferentiateSingleStmt(init) : StmtDiff{};
// Save the isInsideLoop value (we may be inside another loop).
llvm::SaveAndRestore<bool> SaveIsInsideLoop(isInsideLoop);
isInsideLoop = true;
StmtDiff condVarRes;
VarDecl* condVarClone = nullptr;
if (FS->getConditionVariable()) {
condVarRes = DifferentiateSingleStmt(FS->getConditionVariableDeclStmt());
Decl* decl = cast<DeclStmt>(condVarRes.getStmt())->getSingleDecl();
condVarClone = cast<VarDecl>(decl);
}
// FIXME: for now we assume that cond has no differentiable effects,
// but it is not generally true, e.g. for (...; (x = y); ...)...
StmtDiff cond;
if (FS->getCond())
cond = Visit(FS->getCond());
auto IDRE = dyn_cast<DeclRefExpr>(FS->getInc());
const Expr* inc = IDRE ? Visit(FS->getInc()).getExpr() : FS->getInc();
// Differentiate the increment expression of the for loop
// incExprDiff.getExpr() is the reconstructed expression, incDiff.getStmt()
// a block with all the intermediate statements used to reconstruct it on
// the forward pass, incDiff.getStmt_dx() is the reverse pass block.
StmtDiff incDiff;
StmtDiff incExprDiff;
if (inc)
std::tie(incDiff, incExprDiff) = DifferentiateSingleExpr(inc);
Expr* incResult = nullptr;
// If any additional statements were created, enclose them into lambda.
CompoundStmt* Additional = cast<CompoundStmt>(incDiff.getStmt());
bool anyNonExpr = std::any_of(Additional->body_begin(),
Additional->body_end(),
[](Stmt* S) { return !isa<Expr>(S); });
if (anyNonExpr) {
incResult = wrapInLambda(*this, m_Sema, inc, [&] {
std::tie(incDiff, incExprDiff) = DifferentiateSingleExpr(inc);
for (Stmt* S : cast<CompoundStmt>(incDiff.getStmt())->body())
addToCurrentBlock(S);
addToCurrentBlock(incDiff.getExpr());
});
}
// Otherwise, join all exprs by comma operator.
else if (incExprDiff.getExpr()) {
auto CommaJoin = [this](Expr* Acc, Stmt* S) {
Expr* E = cast<Expr>(S);
return BuildOp(BO_Comma, E, BuildParens(Acc));
};
incResult = std::accumulate(Additional->body_rbegin(),
Additional->body_rend(),
incExprDiff.getExpr(),
CommaJoin);
}
const Stmt* body = FS->getBody();
StmtDiff BodyDiff = DifferentiateLoopBody(body, loopCounter,
condVarRes.getStmt_dx(),
incDiff.getStmt_dx(),
/*isForLoop=*/true);
Stmt* Forward = new (m_Context) ForStmt(m_Context,
initResult.getStmt(),
cond.getExpr(),
condVarClone,
incResult,
BodyDiff.getStmt(),
noLoc,
noLoc,
noLoc);
// Create a condition testing counter for being zero, and its decrement.
// To match the number of iterations in the forward pass, the reverse loop
// will look like: for(; Counter; Counter--) ...
Expr*
CounterCondition = loopCounter.getCounterConditionResult().get().second;
Expr* CounterDecrement = loopCounter.getCounterDecrement();
Stmt* ReverseResult = BodyDiff.getStmt_dx();
if (!ReverseResult)
ReverseResult = new (m_Context) NullStmt(noLoc);
Stmt* Reverse = new (m_Context) ForStmt(m_Context,
nullptr,
CounterCondition,
nullptr,
CounterDecrement,
ReverseResult,
noLoc,
noLoc,
noLoc);
addToCurrentBlock(Forward, direction::forward);
Forward = endBlock(direction::forward);
addToCurrentBlock(loopCounter.getPop(), direction::reverse);
addToCurrentBlock(Reverse, direction::reverse);
Reverse = endBlock(direction::reverse);
endScope();
return {unwrapIfSingleStmt(Forward), unwrapIfSingleStmt(Reverse)};
}
StmtDiff
ReverseModeVisitor::VisitCXXDefaultArgExpr(const CXXDefaultArgExpr* DE) {
return Visit(DE->getExpr(), dfdx());
}
StmtDiff
ReverseModeVisitor::VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr* BL) {
return Clone(BL);
}
StmtDiff ReverseModeVisitor::VisitReturnStmt(const ReturnStmt* RS) {
// Initially, df/df = 1.
const Expr* value = RS->getRetValue();
QualType type = value->getType();
auto dfdf = m_Pullback;
if (isa<FloatingLiteral>(dfdf) | isa<IntegerLiteral>(dfdf)) {
ExprResult tmp = dfdf;