Commit Graph

121 Commits

Author SHA1 Message Date
Anton Korobeynikov
89a7663f1d [AutoDiff] Initial support for differentiation of throwing functions (#82653)
This adds initial support for differentiation of functions that may produce `Error` result. 

Essentially we wrap the pullback into `Optional` and emit a diamond-shape control flow pattern depending on whether the pullback value is available or not. VJP emission was modified to accommodate for this. In addition to this, some additional tricks are required as `try_apply` result is not available in the instruction parent block, it is available in normal successor basic block.

As a result we can now:
- differentiate an active `try_apply` result (that would be produced from `do ... try .. catch` constructions)
- `try_apply` when error result is unreachable (usually `try!` and similar source code constructs)
- Support (some) throwing functions with builtin differentiation operators. stdlib change will follow. Though we cannot support typed throws here (yet)
- Correctly propagate error types during currying around differentiable functions as well as type-checking for `@derivative(of:)` attribute, so we can register custom derivatives for functions producing error result
- Added custom derivative for `Optional.??` operator (note that support here is not yet complete as we cannot differentiate through autoclosures, so `x ?? y` works only if `y` is not active, e.g. a constant value).

Some fixes here and there
2025-11-06 13:12:43 -08:00
Anton Korobeynikov
186f88bead [AutoDiff] Fix two issues related with emission of differentiability witnesses (#80983)
1. When differentiable nested function (closure) is specialized by capture promotion pass ensure we generate a differentiability witness for the specialized function as well. Ensure the original witness is removed if the original function becomes dead. 
2. Differentiability witnesses for a function could originate either from its `@differentiable` attribute or from explicit `@derivative(of:)` attribute on the derivative. In the latter case the derivative itself might not be emitted, while original function is (e.g. original function is `@inlineable`, but derivative is `@usableFromInline`). Previously both cases were handled only when function body was emitted. As a result we missed witness in the aforementioned case. Ensure the
differentiability witness originating from `@derivative(of:)` is emitted even if we're not going to emit body of the derivative.

Fixes #59135
2025-10-24 20:02:08 -07:00
Anton Korobeynikov
e6409d7d9d Correctly handle multiple semantic results for autodiff subset differential thunks (#84366)
Fixes https://github.com/swiftlang/swift/issues/84365
2025-09-19 13:54:30 -07:00
Eric Miotto
1034a7a24b Do not an AutoDiff test on backdeployment configurations 2025-08-07 15:13:44 -07:00
Anton Korobeynikov
799e0f81b0 [AutoDiff] Correct propagate adjoints for array literal values (#81676)
Fixes #81607
2025-05-22 03:03:28 -07:00
Erik Eckstein
8cf4e34cc1 RedundantLoadElimination: support replacing a redundant copy_addr with a store
For example:
```
  %0 = load %1
  copy_addr %1 to %2
```
->
```
  %0 = load %1
  store %0 to %2
```

This is important for MandatoryRedundantLoadElimination to be able to create statically initialized globals in the mandatory pipeline.
For example:
```
public struct MyStruct {
  public static let r: Range<Int> = 1 ..< 3
}

```
gets a statically initialized global, even at Onone, with this improvement.

rdar://149356742
2025-04-23 11:57:28 +02:00
Daniil Kovalev
1a42a0ce5f [AutoDiff] Support curry thunks differentiation in fragile funcs (#77615)
Inside fragile functions, we expect function derivatives to be public, which could be achieved by either explicitly marking the functions as differentiable or having a public explicit derivative defined for them. This is obviously not
possible for single and double curry thunks which are a special case of `AutoClosureExpr`.

Instead of looking at the thunk itself, we unwrap it and look at the function being wrapped. While the thunk itself and its differentiability witness will not have public visibility, it's not an issue for the case where the function being wrapped (and its witness) have public visibility.

Fixes #54819
Fixes #75776
2025-02-17 14:43:50 -08:00
Anton Korobeynikov
1e7a1d91fc Emit reabstraction thunks for implicit conversions between T.TangentType and Optional<T>.TangentType (#78076) 2025-02-05 20:57:52 -08:00
Anton Korobeynikov
216111172e Explicitly use minimal type expansion for autodiff-related types (e.g. parameters and pullback result types) (#77831)
As autodiff happens on function types it is not in general possible to determine the real expansion context of the function being differentiated. Use of minimal context is a conservative approach that should work even when libraty evolution mode is enabled.

Fixes #55179
2024-12-02 15:02:09 -08:00
Erik Eckstein
7cceaff5f3 SIL: don't print operand types in textual SIL
Type annotations for instruction operands are omitted, e.g.

```
  %3 = struct $S(%1, %2)
```

Operand types are redundant anyway and were only used for sanity checking in the SIL parser.

But: operand types _are_ printed if the definition of the operand value was not printed yet.
This happens:

* if the block with the definition appears after the block where the operand's instruction is located

* if a block or instruction is printed in isolation, e.g. in a debugger

The old behavior can be restored with `-Xllvm -sil-print-types`.
This option is added to many existing test files which check for operand types in their check-lines.
2024-11-21 18:49:52 +01:00
swift-ci
f8b387573c Merge remote-tracking branch 'origin/main' into rebranch 2024-10-19 23:34:52 -07:00
Allan Shortlidge
6f55aa4170 Tests: Remove -disable-availability-checking in tests that use opaque types.
Use the `%target-swift-5.1-abi-triple` substitution to compile the tests for
deployment to the minimum OS versions required for use of opaque types, instead
of disabling availability checking.
2024-10-19 19:39:18 -07:00
swift-ci
0a99f57502 Merge remote-tracking branch 'origin/main' into rebranch 2024-07-26 17:16:44 -07:00
Anton Korobeynikov
a751b076b6 Fixes inject_enum_addr handling: (#75459)
- Ensure it really accumulates the adjoint buffer
- Handle Optional.none case when there is no value to propagate to

Fixes #75280
2024-07-26 17:04:26 -07:00
Felipe de Azevedo Piovezan
a321b0afe0 [DebugInfo] Update tests to expect new LLVM debug format 2024-07-23 11:06:12 -07:00
swift-ci
e650b133a7 Merge remote-tracking branch 'origin/main' into rebranch 2024-07-04 21:13:51 -07:00
Anton Korobeynikov
f8141e27b1 Ensure we are materializing adjoint value into buffer correctly for optionals: (#74964)
- Ue enum $Optional<T.TangentVector>, #Optional.some!enumelt, %wrappedAdjoint : $T for objects
- Use inject_enum_addr %optArgBuf : $*Optional<T.TangentVector>, #Optional.some!enumelt for addresses

Fixes #74841
2024-07-04 20:53:59 -07:00
swift-ci
e072d4635c Merge remote-tracking branch 'origin/main' into rebranch 2024-07-04 20:53:57 -07:00
Anton Korobeynikov
080a82ba5f Ensure we emit strong_release only for scalar values inside emitDestroyOperation (#74965) 2024-07-04 20:52:10 -07:00
swift-ci
acb84b4fd0 Merge remote-tracking branch 'origin/main' into rebranch 2024-06-05 19:54:38 -07:00
Alex Lorenz
0f9a69c712 android test fixes 2024-05-28 12:59:26 -07:00
swift-ci
112cf2df58 Merge remote-tracking branch 'origin/main' into rebranch 2024-05-24 10:15:07 -07:00
Ellie Shin
5ccc4cd394 SIL function can be serialized with different kinds: [serialized] or
[serialized_for_package] if Package CMO is enabled. The latter kind
allows a function to be serialized even if it contains loadable types,
if Package CMO is enabled. Renamed IsSerialized_t as SerializedKind_t.

The tri-state serialization kind requires validating inlinability
depending on the serialization kinds of callee vs caller; e.g. if the
callee is [serialized_for_package], the caller must be _not_ [serialized].
Renamed `hasValidLinkageForFragileInline` as `canBeInlinedIntoCaller`
that takes in its caller's SerializedKind as an argument. Another argument
`assumeFragileCaller` is also added to ensure that the calle sites of
this function know the caller is serialized unless it's called for SIL
inlining optimization passes.

The [serialized_for_package] attribute is allowed for SIL function, global var,
v-table, and witness-table.

Resolves rdar://128406520
2024-05-23 15:53:02 -07:00
Hamish Knight
782ae72efd Merge branch 'main' into merge-rebranch 2024-05-23 20:03:52 +01:00
Emil Pedersen
5606fbc1d6 [IRGenDebugInfo] Disable usage of dbg.declare in optimized code
Except for the async context, where it is needed (arguments
within an async function).

We don't support dbg.declare in optimized code, as variables can
be moved by SIL optimization passes. If a partial store is
eliminated, we want a dbg.value on the allocation, and another
dbg.value with a fragment in place of the partial store.

rdar://128155050
2024-05-22 09:35:37 -07:00
Dario Rexin
40f516a1b8 [Test] Fix signature mismatch in issue-58123-invalid-debug-info.swift
rdar://128431000

Made the matcher more robust for potential future added modifiers.
2024-05-21 15:17:17 -07:00
Emil Pedersen
523a769e34 [DebugInfo] [Mem2Reg] Move debug info promotion to salvageDebugInfo 2024-04-23 13:12:21 -07:00
Emil Pedersen
efa09088ac Revert "[DebugInfo][SIL] Introduce the 'implicit' attribute for debug variable"
This reverts commit e63632fda8.

rdar://125939953
2024-04-04 17:23:32 -07:00
Anton Korobeynikov
f5cce4784f Make autdiff more robust in presence of unreachable blocks (#71356)
Unreachable blocks possess some challenges to autodiff since in reverse pass (pullback generation) we need to execute the function backwards, pushing the values from return BB back to entry block. As a result, unreachable blocks might become reachable from the return BB and this might cause all kind of issues.
2024-02-03 08:33:36 -08:00
Erik Eckstein
c89df9ec98 Mandatory optimizations: constant fold boolean literals before the DefiniteInitialization pass
Add a new mandatory BooleanLiteralFolding pass which constant folds conditional branches with boolean literals as operands.

```
  %1 = integer_literal -1
  %2 = apply %bool_init(%1)   // Bool.init(_builtinBooleanLiteral:)
  %3 = struct_extract %2, #Bool._value
  cond_br %3, bb1, bb2
```
->
```
  ...
  br bb1
```

This pass is intended to run before DefiniteInitialization, where mandatory inlining and constant folding didn't run, yet (which would perform this kind of optimization).
This optimization is required to let DefiniteInitialization handle boolean literals correctly.
For example in infinite loops:

```
   init() {
     while true {           // DI need to know that there is no loop exit from this while-statement
       if some_condition {
         member_field = init_value
         break
       }
     }
   }
```
2024-01-10 16:15:57 +01:00
Anton Korobeynikov
4d391f0f8e Add Differentiable requirements to pattern substitutions / pattern generic signature (#68777)
Add `Differentiable` requirements to pattern substitutions / pattern generic signature when calculating constrained function type. Also, add requirements for differentiable results as well.

Fixes #65487
2023-10-04 14:48:03 -07:00
Kshitij Jain
d971f125d9 [AutoDiff] Handle materializing adjoints with non-differentiable fields (#67319) 2023-09-12 14:22:41 -07:00
Anton Korobeynikov
03334a8f92 [AutoDiff] Generalize handling of semantic result parameters (#67230)
Introduce the notion of "semantic result parameter". Handle differentiation of inouts via semantic result parameter abstraction. Do not consider non-wrt semantic result parameters as semantic results

Fixes #67174
2023-08-03 09:33:11 -07:00
Arnold Schwaighofer
0b6db0afc4 Fix test/AutoDiff directory 2023-06-20 12:47:56 -07:00
Arnold Schwaighofer
c1a93e0bde Move tests over to use the %use_no_opaque_pointers option 2023-06-14 10:49:48 -07:00
Anton Korobeynikov
0b235a7aac [AutoDiff[ Preserve substitutions maps while calculating derivative types (#65451)
The substituon map might contain proper specialization (e.g. t_0_0 -> Double) that is required to fully specify a derivate type (e.g. during reabstraction conversion from fully specified function type to a substituted one)

Fixes #65073
2023-04-26 23:11:15 -07:00
Erik Eckstein
e356b122f6 tests: disable AutoDiff/compiler_crashers_fixed/issue-55852-tangent-value-category-mismatch.swift on linux
Sometimes the linker crashes on linux
2023-04-18 14:38:25 +02:00
Erik Eckstein
0794eb3c57 tests: don't run AutoDiff/compiler_crashers_fixed/58660-conflicting-debug-info-inlining.swift on linux 2023-04-18 10:17:51 +02:00
Slava Pestov
a8cec8e268 Disable AutoDiff/compiler_crashers_fixed/58660-conflicting-debug-info-inlining.swift on Linux 2023-03-15 00:56:29 -04:00
Anton Korobeynikov
869fc1792e [AutoDiff] Ensure autodiff code does not ignore getSingleTerminatorOperands return value (#64200)
Also extend activity analysis to handle `try_apply` normal result properly. Add testcase from #63728
2023-03-08 10:10:22 -08:00
swift-ci
ee20e6066f Merge remote-tracking branch 'origin/main' into rebranch 2023-02-19 18:54:26 -08:00
Anton Korobeynikov
11de73639c [AutoDiff] Unwrap the top level of linear map tuple when it is possible (#63770)
This essentially passes the members of a linear map tuple as individual arguments. It yields few nice simplifications:

 * No linear map tuples at all for getters / setters
 * No tuple formation / deconstruction around pullbacks
 * Pullbacks with loops still use heap-allocated tuples
2023-02-19 18:46:49 -08:00
swift-ci
d542b741b6 Merge remote-tracking branch 'origin/main' into rebranch 2023-02-08 07:54:19 -08:00
Anton Korobeynikov
d2e022d5b4 Remove linear map structs and use plain tuples instead. (#63444)
The changes are intentionally were made close to the original implementation w/o possible simplifications to ease the review

Fixes #63207, supersedes #63379 (and fixes #63234)
2023-02-08 07:42:54 -08:00
swift-ci
73883dd0b3 Merge remote-tracking branch 'origin/main' into rebranch 2023-01-20 10:48:41 -08:00
Alex Hoppen
069f382023 Disable rdar74087329-debug-scope-trampoline-blocks.swift
This is failing on the Linux bots. Let’s disable the test for now. #63107 tracks the actual failure.
2023-01-20 19:40:24 +01:00
Erik Eckstein
712fd7922b Merge remote-tracking branch 'origin/main' into rebranch 2023-01-09 08:48:47 +01:00
Anton Korobeynikov
6d657c90af [AutoDiff] Refine debug info emitted for adjoint buffers (#62779)
Single input variable might yield multiple adjoint buffers if control flow is involved. Therefore we cannot simply transfer debug info  from the input variable: it will be invalid as we will end with multiple locations for a single "source" variable, and, even worse, might end with conflicting debug info as different buffers might be optimized
differently.

We do:
  - Drop input argument number. This must be unique and we're not
  - Correct variable name
2023-01-06 14:34:16 -08:00
swift-ci
84236ec390 Merge remote-tracking branch 'origin/main' into rebranch 2022-12-04 01:13:44 -08:00
Anthony Latsis
4cb63c8a0f [NFC] Migrate remnant Jira issue references to GitHub issues 2022-12-04 08:20:34 +03:00