Skip to content

Commit

Permalink
Fix the derivative of string literals in forward mode
Browse files Browse the repository at this point in the history
This commit makes Clad set the derivative of string literals
to an empty string in the forward mode. Differentiating string
literals used to produce integer zero literals previously.
  • Loading branch information
gojakuch committed Jul 4, 2024
1 parent 645d2b6 commit 4ac8ca5
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 4 deletions.
7 changes: 3 additions & 4 deletions lib/Differentiator/BaseForwardModeVisitor.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -1662,10 +1662,9 @@ BaseForwardModeVisitor::VisitCharacterLiteral(const CharacterLiteral* CL) {
}

StmtDiff BaseForwardModeVisitor::VisitStringLiteral(const StringLiteral* SL) {
llvm::APInt zero(m_Context.getIntWidth(m_Context.IntTy), /*value*/ 0);
auto* constant0 =
IntegerLiteral::Create(m_Context, zero, m_Context.IntTy, noLoc);
return StmtDiff(Clone(SL), constant0);
return StmtDiff(Clone(SL), StringLiteral::Create(
m_Context, "", SL->getKind(), SL->isPascal(),
SL->getType(), utils::GetValidSLoc(m_Sema)));
}

StmtDiff BaseForwardModeVisitor::VisitWhileStmt(const WhileStmt* WS) {
Expand Down
33 changes: 33 additions & 0 deletions test/FirstDerivative/Variables.C
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@

#include "clad/Differentiator/Differentiator.h"
#include <cmath>
#include <string>

double f_x(double x) {
double t0 = x;
Expand Down Expand Up @@ -86,12 +87,44 @@ double f_sin(double x, double y) {
// CHECK-NEXT: return _d_xt + _d_yt;
// CHECK-NEXT: }

double f_string(double x) {
const char *s = "string literal";
return x;
}

// CHECK: double f_string_darg0(double x) {
// CHECK-NEXT: double _d_x = 1;
// CHECK-NEXT: const char *_d_s = "";
// CHECK-NEXT: const char *s = "string literal";
// CHECK-NEXT: return _d_x;
// CHECK-NEXT: }

namespace clad {
namespace custom_derivatives {
clad::ValueAndPushforward<double, double> string_test_pushforward(double x, const char s[], double _d_x, const char *_d_s) {
return {0, 0};
}
}}
double string_test(double x, const char s[]) {
return 1;
}
double f_string_call(double x) {
return string_test(x, "string literal");
}

// CHECK: double f_string_call_darg0(double x) {
// CHECK-NEXT: double _d_x = 1;
// CHECK-NEXT: clad::ValueAndPushforward<double, double> _t0 = clad::custom_derivatives::string_test_pushforward(x, "string literal", _d_x, "");
// CHECK-NEXT: return _t0.pushforward;
// CHECK-NEXT: }

int main() {
clad::differentiate(f_x, 0);
clad::differentiate(f_ops1, 0);
clad::differentiate(f_ops2, 0);
clad::differentiate(f_sin, 0);
clad::differentiate(f_string, 0);
clad::differentiate(f_string_call, 0);
}


0 comments on commit 4ac8ca5

Please sign in to comment.