|
22 | 22 | #include "swift/AST/DiagnosticsSIL.h"
|
23 | 23 | #include "swift/AST/ForeignInfo.h"
|
24 | 24 | #include "swift/AST/GenericEnvironment.h"
|
| 25 | +#include "swift/AST/GenericSignatureBuilder.h" |
25 | 26 | #include "swift/AST/Module.h"
|
26 | 27 | #include "swift/AST/ModuleLoader.h"
|
27 | 28 | #include "swift/AST/ProtocolConformance.h"
|
@@ -190,6 +191,196 @@ SILFunctionType::getWitnessMethodClass(SILModule &M) const {
|
190 | 191 | return nullptr;
|
191 | 192 | }
|
192 | 193 |
|
| 194 | +// Returns the canonical generic signature for an autodiff derivative function |
| 195 | +// given an existing derivative function generic signature. All |
| 196 | +// differentiability parameters are required to conform to `Differentiable`. |
| 197 | +static CanGenericSignature getAutoDiffDerivativeFunctionGenericSignature( |
| 198 | + CanGenericSignature derivativeFnGenSig, |
| 199 | + ArrayRef<SILParameterInfo> originalParameters, |
| 200 | + IndexSubset *parameterIndices, ModuleDecl *module) { |
| 201 | + if (!derivativeFnGenSig) |
| 202 | + return nullptr; |
| 203 | + auto &ctx = module->getASTContext(); |
| 204 | + GenericSignatureBuilder builder(ctx); |
| 205 | + // Add derivative function generic signature. |
| 206 | + builder.addGenericSignature(derivativeFnGenSig); |
| 207 | + // All differentiability parameters are required to conform to |
| 208 | + // `Differentiable`. |
| 209 | + auto source = |
| 210 | + GenericSignatureBuilder::FloatingRequirementSource::forAbstract(); |
| 211 | + auto *differentiableProtocol = |
| 212 | + ctx.getProtocol(KnownProtocolKind::Differentiable); |
| 213 | + for (unsigned paramIdx : parameterIndices->getIndices()) { |
| 214 | + auto paramType = originalParameters[paramIdx].getInterfaceType(); |
| 215 | + Requirement req(RequirementKind::Conformance, paramType, |
| 216 | + differentiableProtocol->getDeclaredType()); |
| 217 | + builder.addRequirement(req, source, module); |
| 218 | + } |
| 219 | + return std::move(builder) |
| 220 | + .computeGenericSignature(SourceLoc(), /*allowConcreteGenericParams*/ true) |
| 221 | + ->getCanonicalSignature(); |
| 222 | +} |
| 223 | + |
| 224 | +CanSILFunctionType SILFunctionType::getAutoDiffDerivativeFunctionType( |
| 225 | + IndexSubset *parameterIndices, unsigned resultIndex, |
| 226 | + AutoDiffDerivativeFunctionKind kind, TypeConverter &TC, |
| 227 | + LookupConformanceFn lookupConformance, |
| 228 | + CanGenericSignature derivativeFnGenSig, bool isReabstractionThunk) { |
| 229 | + auto &ctx = getASTContext(); |
| 230 | + |
| 231 | + // Returns true if `index` is a differentiability parameter index. |
| 232 | + auto isDiffParamIndex = [&](unsigned index) -> bool { |
| 233 | + return index < parameterIndices->getCapacity() && |
| 234 | + parameterIndices->contains(index); |
| 235 | + }; |
| 236 | + |
| 237 | + // Calculate differentiability parameter infos. |
| 238 | + SmallVector<SILParameterInfo, 4> diffParams; |
| 239 | + for (auto valueAndIndex : enumerate(getParameters())) |
| 240 | + if (isDiffParamIndex(valueAndIndex.index())) |
| 241 | + diffParams.push_back(valueAndIndex.value()); |
| 242 | + |
| 243 | + // Get the canonical derivative function generic signature. |
| 244 | + if (!derivativeFnGenSig) |
| 245 | + derivativeFnGenSig = getSubstGenericSignature(); |
| 246 | + derivativeFnGenSig = getAutoDiffDerivativeFunctionGenericSignature( |
| 247 | + derivativeFnGenSig, getParameters(), parameterIndices, &TC.M); |
| 248 | + |
| 249 | + // Given a type, returns its formal SIL parameter info. |
| 250 | + auto getTangentParameterInfoForOriginalResult = |
| 251 | + [&](CanType tanType, ResultConvention origResConv) -> SILParameterInfo { |
| 252 | + AbstractionPattern pattern(derivativeFnGenSig, tanType); |
| 253 | + auto &tl = |
| 254 | + TC.getTypeLowering(pattern, tanType, TypeExpansionContext::minimal()); |
| 255 | + ParameterConvention conv; |
| 256 | + switch (origResConv) { |
| 257 | + case ResultConvention::Owned: |
| 258 | + case ResultConvention::Autoreleased: |
| 259 | + conv = tl.isTrivial() ? ParameterConvention::Direct_Unowned |
| 260 | + : ParameterConvention::Direct_Guaranteed; |
| 261 | + break; |
| 262 | + case ResultConvention::Unowned: |
| 263 | + case ResultConvention::UnownedInnerPointer: |
| 264 | + conv = ParameterConvention::Direct_Unowned; |
| 265 | + break; |
| 266 | + case ResultConvention::Indirect: |
| 267 | + conv = ParameterConvention::Indirect_In_Guaranteed; |
| 268 | + break; |
| 269 | + } |
| 270 | + return {tanType, conv}; |
| 271 | + }; |
| 272 | + |
| 273 | + // Given a type, returns its formal SIL result info. |
| 274 | + auto getTangentResultInfoForOriginalParameter = |
| 275 | + [&](CanType tanType, ParameterConvention origParamConv) -> SILResultInfo { |
| 276 | + AbstractionPattern pattern(derivativeFnGenSig, tanType); |
| 277 | + auto &tl = |
| 278 | + TC.getTypeLowering(pattern, tanType, TypeExpansionContext::minimal()); |
| 279 | + ResultConvention conv; |
| 280 | + switch (origParamConv) { |
| 281 | + case ParameterConvention::Direct_Owned: |
| 282 | + case ParameterConvention::Direct_Guaranteed: |
| 283 | + case ParameterConvention::Direct_Unowned: |
| 284 | + conv = |
| 285 | + tl.isTrivial() ? ResultConvention::Unowned : ResultConvention::Owned; |
| 286 | + break; |
| 287 | + case ParameterConvention::Indirect_In: |
| 288 | + case ParameterConvention::Indirect_Inout: |
| 289 | + case ParameterConvention::Indirect_In_Constant: |
| 290 | + case ParameterConvention::Indirect_In_Guaranteed: |
| 291 | + case ParameterConvention::Indirect_InoutAliasable: |
| 292 | + conv = ResultConvention::Indirect; |
| 293 | + break; |
| 294 | + } |
| 295 | + return {tanType, conv}; |
| 296 | + }; |
| 297 | + |
| 298 | + CanSILFunctionType closureType; |
| 299 | + switch (kind) { |
| 300 | + case AutoDiffDerivativeFunctionKind::JVP: { |
| 301 | + SmallVector<SILParameterInfo, 8> differentialParams; |
| 302 | + for (auto ¶m : diffParams) { |
| 303 | + auto paramTan = |
| 304 | + param.getInterfaceType()->getAutoDiffTangentSpace(lookupConformance); |
| 305 | + assert(paramTan && "Parameter type does not have a tangent space?"); |
| 306 | + differentialParams.push_back( |
| 307 | + {paramTan->getCanonicalType(), param.getConvention()}); |
| 308 | + } |
| 309 | + SmallVector<SILResultInfo, 8> differentialResults; |
| 310 | + auto &result = getResults()[resultIndex]; |
| 311 | + auto resultTan = |
| 312 | + result.getInterfaceType()->getAutoDiffTangentSpace(lookupConformance); |
| 313 | + assert(resultTan && "Result type does not have a tangent space?"); |
| 314 | + differentialResults.push_back( |
| 315 | + {resultTan->getCanonicalType(), result.getConvention()}); |
| 316 | + closureType = SILFunctionType::get( |
| 317 | + /*genericSignature*/ nullptr, ExtInfo(), SILCoroutineKind::None, |
| 318 | + ParameterConvention::Direct_Guaranteed, differentialParams, {}, |
| 319 | + differentialResults, None, getSubstitutions(), |
| 320 | + isGenericSignatureImplied(), ctx); |
| 321 | + break; |
| 322 | + } |
| 323 | + case AutoDiffDerivativeFunctionKind::VJP: { |
| 324 | + SmallVector<SILParameterInfo, 8> pullbackParams; |
| 325 | + auto &origRes = getResults()[resultIndex]; |
| 326 | + auto resultTan = |
| 327 | + origRes.getInterfaceType()->getAutoDiffTangentSpace(lookupConformance); |
| 328 | + assert(resultTan && "Result type does not have a tangent space?"); |
| 329 | + pullbackParams.push_back(getTangentParameterInfoForOriginalResult( |
| 330 | + resultTan->getCanonicalType(), origRes.getConvention())); |
| 331 | + SmallVector<SILResultInfo, 8> pullbackResults; |
| 332 | + for (auto ¶m : diffParams) { |
| 333 | + auto paramTan = |
| 334 | + param.getInterfaceType()->getAutoDiffTangentSpace(lookupConformance); |
| 335 | + assert(paramTan && "Parameter type does not have a tangent space?"); |
| 336 | + pullbackResults.push_back(getTangentResultInfoForOriginalParameter( |
| 337 | + paramTan->getCanonicalType(), param.getConvention())); |
| 338 | + } |
| 339 | + closureType = SILFunctionType::get( |
| 340 | + /*genericSignature*/ nullptr, ExtInfo(), SILCoroutineKind::None, |
| 341 | + ParameterConvention::Direct_Guaranteed, pullbackParams, {}, |
| 342 | + pullbackResults, {}, getSubstitutions(), isGenericSignatureImplied(), |
| 343 | + ctx); |
| 344 | + break; |
| 345 | + } |
| 346 | + } |
| 347 | + |
| 348 | + SmallVector<SILParameterInfo, 4> newParameters; |
| 349 | + newParameters.reserve(getNumParameters()); |
| 350 | + for (auto ¶m : getParameters()) { |
| 351 | + newParameters.push_back(param.getWithInterfaceType( |
| 352 | + param.getInterfaceType()->getCanonicalType(derivativeFnGenSig))); |
| 353 | + } |
| 354 | + // TODO(TF-1124): Upstream reabstraction thunk derivative typing rules. |
| 355 | + // Blocked by TF-1125: `SILFunctionType::getWithDifferentiability`. |
| 356 | + SmallVector<SILResultInfo, 4> newResults; |
| 357 | + newResults.reserve(getNumResults() + 1); |
| 358 | + for (auto &result : getResults()) { |
| 359 | + newResults.push_back(result.getWithInterfaceType( |
| 360 | + result.getInterfaceType()->getCanonicalType(derivativeFnGenSig))); |
| 361 | + } |
| 362 | + newResults.push_back({closureType->getCanonicalType(derivativeFnGenSig), |
| 363 | + ResultConvention::Owned}); |
| 364 | + // Derivative function type has a generic signature only if the original |
| 365 | + // function type does, and if `derivativeFnGenSig` does not have all concrete |
| 366 | + // generic parameters. |
| 367 | + CanGenericSignature canGenSig; |
| 368 | + if (getSubstGenericSignature() && derivativeFnGenSig && |
| 369 | + !derivativeFnGenSig->areAllParamsConcrete()) |
| 370 | + canGenSig = derivativeFnGenSig; |
| 371 | + // If original function is `@convention(c)`, the derivative function should |
| 372 | + // have `@convention(thin)`. IRGen does not support `@convention(c)` functions |
| 373 | + // with multiple results. |
| 374 | + auto extInfo = getExtInfo(); |
| 375 | + if (getRepresentation() == SILFunctionTypeRepresentation::CFunctionPointer) |
| 376 | + extInfo = extInfo.withRepresentation(SILFunctionTypeRepresentation::Thin); |
| 377 | + return SILFunctionType::get(canGenSig, extInfo, getCoroutineKind(), |
| 378 | + getCalleeConvention(), newParameters, getYields(), |
| 379 | + newResults, getOptionalErrorResult(), |
| 380 | + getSubstitutions(), isGenericSignatureImplied(), |
| 381 | + ctx, getWitnessMethodConformanceOrInvalid()); |
| 382 | +} |
| 383 | + |
193 | 384 | static CanType getKnownType(Optional<CanType> &cacheSlot, ASTContext &C,
|
194 | 385 | StringRef moduleName, StringRef typeName) {
|
195 | 386 | if (!cacheSlot) {
|
|
0 commit comments