Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions include/swift/AST/ASTBridging.h
Original file line number Diff line number Diff line change
Expand Up @@ -305,6 +305,10 @@ bool BridgedASTContext_testCanImport(BridgedASTContext cContext,
SWIFT_NAME("getter:BridgedASTContext.staticBuildConfigurationPtr(self:)")
void * _Nonnull BridgedASTContext_staticBuildConfiguration(BridgedASTContext cContext);

SWIFT_NAME("BridgedASTContext.hasTargetFeature(self:_:)")
bool BridgedASTContext_hasTargetFeature(BridgedASTContext cContext,
BridgedStringRef cName);

//===----------------------------------------------------------------------===//
// MARK: AST nodes
//===----------------------------------------------------------------------===//
Expand Down
4 changes: 4 additions & 0 deletions include/swift/AST/ClangModuleLoader.h
Original file line number Diff line number Diff line change
Expand Up @@ -143,6 +143,10 @@ class ClangModuleLoader : public ModuleLoader {
/// for use by IRGen/CodeGen clients)
virtual clang::TargetInfo &getModuleAvailabilityTarget() const = 0;

/// Determine whether the given ISA feature name (e.g. "avx2") is
/// part of the module codegen CPU/feature baseline.
virtual bool hasTargetFeature(StringRef featureName) const = 0;

virtual clang::ASTContext &getClangASTContext() const = 0;
virtual clang::Preprocessor &getClangPreprocessor() const = 0;
virtual clang::Sema &getClangSema() const = 0;
Expand Down
3 changes: 3 additions & 0 deletions include/swift/Basic/Features.def
Original file line number Diff line number Diff line change
Expand Up @@ -692,6 +692,9 @@ EXPERIMENTAL_FEATURE(TargetAttribute, true)
/// Enable distributed actors in Embedded Swift.
EXPERIMENTAL_FEATURE(EmbeddedDistributed, false)

/// Enable `#if _hasTargetFeature(...)`, a build-time ISA feature query.
EXPERIMENTAL_FEATURE(TargetFeaturePredicate, false)

#undef EXPERIMENTAL_FEATURE_EXCLUDED_FROM_MODULE_INTERFACE
#undef EXPERIMENTAL_FEATURE
#undef UPCOMING_FEATURE
Expand Down
1 change: 1 addition & 0 deletions include/swift/ClangImporter/ClangImporter.h
Original file line number Diff line number Diff line change
Expand Up @@ -544,6 +544,7 @@ class ClangImporter final : public ClangModuleLoader {
std::vector<std::string> &swiftArgs);

clang::TargetInfo &getModuleAvailabilityTarget() const override;
bool hasTargetFeature(StringRef featureName) const override;
clang::ASTContext &getClangASTContext() const override;
clang::Preprocessor &getClangPreprocessor() const override;
clang::Sema &getClangSema() const override;
Expand Down
7 changes: 7 additions & 0 deletions lib/AST/Bridging/ASTContextBridging.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
#include "swift/AST/ASTContext.h"
#include "swift/AST/ASTContextGlobalCache.h"
#include "swift/AST/AvailabilitySpec.h"
#include "swift/AST/ClangModuleLoader.h"
#include "swift/Bridging/BasicSwift.h"

using namespace swift;
Expand Down Expand Up @@ -127,6 +128,12 @@ bool BridgedASTContext_testCanImport(BridgedASTContext cContext,
builder.get(), version, versionKind == CanImportUnderlyingVersion);
}

bool BridgedASTContext_hasTargetFeature(BridgedASTContext cContext,
BridgedStringRef cName) {
return cContext.unbridged().getClangModuleLoader()->hasTargetFeature(
cName.unbridged());
}

BridgedAvailabilityMacroMap BridgedASTContext::getAvailabilityMacroMap() const {
return &unbridged().getAvailabilityMacroMap();
}
Expand Down
1 change: 1 addition & 0 deletions lib/AST/FeatureSet.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -510,6 +510,7 @@ UNINTERESTING_FEATURE(CoroutineAccessorsUnwindOnCallerError)
UNINTERESTING_FEATURE(AllowRuntimeSymbolDeclarations)
UNINTERESTING_FEATURE(DistributedActorResignRemoteID)
UNINTERESTING_FEATURE(EmbeddedDistributed)
UNINTERESTING_FEATURE(TargetFeaturePredicate)

static bool usesFeatureCoroutineAccessors(Decl *decl) {
auto accessorDeclUsesFeatureCoroutineAccessors = [](AccessorDecl *accessor) {
Expand Down
7 changes: 7 additions & 0 deletions lib/ASTGen/Sources/ASTGen/CompilerBuildConfiguration.swift
Original file line number Diff line number Diff line change
Expand Up @@ -160,6 +160,13 @@ struct CompilerBuildConfiguration: BuildConfiguration {
staticBuildConfiguration.isActiveTargetObjectFormat(name: name)
}

func hasTargetFeature(name: String) throws -> Bool {
var name = name
return name.withBridgedString { cName in
ctx.hasTargetFeature(cName)
}
}

var targetAtomicBitWidths: [Int] {
staticBuildConfiguration.targetAtomicBitWidths
}
Expand Down
4 changes: 4 additions & 0 deletions lib/ASTGen/Sources/ASTGen/EmbeddedSupport.swift
Original file line number Diff line number Diff line change
Expand Up @@ -128,6 +128,10 @@ struct EmbeddedBuildConfiguration: BuildConfiguration {
return try configuration.isActiveTargetObjectFormat(name: name)
}

func hasTargetFeature(name: String) throws -> Bool {
return try configuration.hasTargetFeature(name: name)
}

var targetAtomicBitWidths: [Int] {
return configuration.targetAtomicBitWidths
}
Expand Down
4 changes: 4 additions & 0 deletions lib/ClangImporter/ClangImporter.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -4480,6 +4480,10 @@ clang::TargetInfo &ClangImporter::getModuleAvailabilityTarget() const {
return Impl.Instance->getTarget();
}

bool ClangImporter::hasTargetFeature(StringRef featureName) const {
return getTargetInfo().hasFeature(featureName);

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm not sure about this implementation. Doesn't the @target attribute change what target features are available within a particular function?

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes, but this is orthogonal. This is meant to support the following idiom:

#if arch(particular processor) && _hasTargetFeature(particular feature)
   ... code optimized for particular ISA ...
#else if arch(other processor) && _hasTargetFeature(other feature)
   ... code optimized for some other ISA ...
#else
   ... general code without any ISA assumptions ...
#endif

@hjyamauchi hjyamauchi Sep 11, 2026 •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes and this allows us to choose among different versions at build time. What I'm aiming for here is the combination of @_target and this so that we can call separate code optimized for different ISA features based on the build-time baseline target CPU, something like:

@_target("sve2")
func foo_sve2() { ... }
@_target("sve")
func foo_sve() { ... }
// default
func foo_default() { ... }

#if _hasTargetFeature("sve2")
foo_sve2()
#elseif _hasTargetFeature("sve")
foo_sve()
#else
foo_default()
#endif

where foo_sve2() is taken when it's built with sve2 and foo_sve() is taken when it's built with sve

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Okay, now put that into a function that uses @target:

@target(particular feature)
func f() {
#if arch(particular processor) && _hasTargetFeature(particular feature)
   ... code optimized for particular ISA ...
#else if arch(other processor) && _hasTargetFeature(other feature)
   ... code optimized for some other ISA ...
#else
   ... general code without any ISA assumptions ...
#endif
}

When arch(particular processor) holds, and the target provided on the command line doesn't imply _hasTargetFeature(particular feature), what should I expect this to do?

@tbkka tbkka Sep 11, 2026 •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

_hasTargetFeature() refers to the current processor architecture being targeted by the current compilation context. This may be affected by compiler command-line options and by surrounding @target() annotations.

In your example here, the presence of @target(particular feature) indicates that this function is being compiled for a processor with that particular feature, so I would expect _hasTargetFeature(particular feature) to evaluate true.

To be honest, this seems like a pointless combination in practice. For an MVP, I'd be happy for _hasTargetFeature() to diagnose when put inside a function with @target() on it.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I still think #if is the right design here. The whole point is being able to choose different implementations at compile time and that's exactly what #if expresses.

As I said, there's not much point to combining these two. Is it feasible to diagnose? I'd have to think about whether I would be willing to just silently ignore @target() for this purpose. Maybe @stephentyrone has some insight?

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Some variation of function multi-versioning could conceivably be an alternative: clang supports a feature where you provide overloads of a function and annotate each one with the particular processor/target feature that it should be used for. This should allow us to defer final function selection until IRGen (or even later).

@DougGregor DougGregor Sep 11, 2026 •

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If we have multi-versioning, do we need this #if _hasTargetFeature?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think #if allows purely compile-time conditional code while multi-versioning involves runtime/link-time checks/indirection. An expected use case is when we are willing to raise baseline target cpu and have multiple builds optimized for each CPU generation. Maybe not be a perfect example but writing code sort of like this would be enabled.

@stephentyrone stephentyrone Sep 13, 2026 •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes, we absolutely need (a good version of) this in the presence of multi-versioning (if anything, it becomes more important, not less). Consider something like a two-register lookup table in SIMD. This is going to get inlined into a multi-versioned function. On arm64, it should become TBL. On baseline x86 it has to be an explicit memory gather. But on x86 with SSSE3 (whether via command line flags, target, or multi-versioning), it should become two PSHUFBs and a blend. On x86 with the right AVX512 extensions, it should be a single instruction. But there's no way to write that in a target-independent manner*. We actually need to have different implementations of the two-register lookup table depending on what features are available in the context we get inlined into.

(*) LLVM has been working on this, so it might be soon, but lots of other things still won't be.

Even if one isn't writing explicit SIMD, I frequently want to use a different algorithm depending on what instructions are available. For instance, in something like Augmented.product from Numerics, we would like to use an FMA-based algorithm when targeting x86 with FMA, but Dekker's hi-lo split algorithm when we do not have FMA available, rather than going through a soft float FMA from the host libm.

}

clang::TargetInfo &ClangImporter::getTargetInfo() const {
return Impl.getCodeGenTargetInfo();
}
Expand Down
16 changes: 16 additions & 0 deletions lib/Parse/ParseIfConfig.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@

#include "swift/AST/ASTBridging.h"
#include "swift/AST/ASTVisitor.h"
#include "swift/AST/ClangModuleLoader.h"
#include "swift/AST/DiagnosticSuppression.h"
#include "swift/AST/DiagnosticsParse.h"
#include "swift/Basic/Assertions.h"
Expand Down Expand Up @@ -394,6 +395,18 @@ class ValidateIfConfigCondition :
return E;
}

if (*KindName == "_hasTargetFeature" &&
Ctx.LangOpts.hasFeature(Feature::TargetFeaturePredicate)) {
auto SLE = dyn_cast<StringLiteralExpr>(Arg);
if (!SLE || SLE->getValue().empty()) {
D.diagnose(ArgLoc, diag::unsupported_platform_condition_argument,
"target feature name");
return nullptr;
}

return E;
}

// ( 'os' | 'arch' | '_endian' | '_pointerBitWidth' | '_runtime' | '_hasAtomicBitWidth' | 'objectFormat' ) '(' identifier ')''
auto Kind = getPlatformConditionKind(*KindName);
if (!Kind.has_value()) {
Expand Down Expand Up @@ -629,6 +642,9 @@ class EvaluateIfConfigCondition :
} else if (KindName == "hasAttribute") {
auto attributeName = getDeclRefStr(Arg);
return hasAttribute(Ctx.LangOpts, attributeName);
} else if (KindName == "_hasTargetFeature") {
auto featureName = cast<StringLiteralExpr>(Arg)->getValue();
return Ctx.getClangModuleLoader()->hasTargetFeature(featureName);
}

auto Val = getDeclRefStr(Arg);
Expand Down
31 changes: 31 additions & 0 deletions test/ModuleInterface/has_target_feature.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
// RUN: %target-swift-emit-module-interface(%t.swiftinterface) %s -target arm64-apple-macosx13.0 -target-cpu apple-a14 -enable-experimental-feature TargetFeaturePredicate -module-name has_target_feature
// RUN: %FileCheck %s < %t.swiftinterface
// RUN: %target-swift-typecheck-module-from-interface(%t.swiftinterface) -module-name has_target_feature

// REQUIRES: swift_feature_TargetFeaturePredicate
// REQUIRES: OS=macosx && CPU=arm64

// Check that hasTargetFeature is retained rather than evaluated away in inlinable function bodies.

// CHECK-LABEL: func hasDotProd
// CHECK: #if $TargetFeaturePredicate
// CHECK-NEXT: #if _hasTargetFeature("dotprod")
// CHECK-NEXT: return true
// CHECK-NEXT: #else
// CHECK-NEXT: return false
// CHECK-NEXT: #endif
// CHECK-NEXT: #else
// CHECK-NEXT: return false
// CHECK-NEXT: #endif
@inlinable
public func hasDotProd() -> Bool {
#if $TargetFeaturePredicate
#if _hasTargetFeature("dotprod")
return true
#else
return false
#endif
#else
return false
#endif
}
46 changes: 46 additions & 0 deletions test/Parse/ConditionalCompilation/has_target_feature.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
// RUN: %swift -typecheck %s -target x86_64-apple-macosx13.0 -target-cpu haswell -enable-experimental-feature TargetFeaturePredicate -parse-stdlib 2>&1 | %FileCheck -check-prefix CHECK-HASWELL %s
// RUN: %swift -typecheck %s -target x86_64-apple-macosx13.0 -target-cpu core2 -enable-experimental-feature TargetFeaturePredicate -parse-stdlib 2>&1 | %FileCheck -check-prefix CHECK-CORE2 %s
// RUN: %swift -typecheck %s -target arm64-apple-macosx13.0 -target-cpu apple-a14 -enable-experimental-feature TargetFeaturePredicate -parse-stdlib 2>&1 | %FileCheck -check-prefix CHECK-A14 %s
// RUN: %swift -typecheck %s -target arm64-apple-macosx13.0 -target-cpu generic -enable-experimental-feature TargetFeaturePredicate -parse-stdlib 2>&1 | %FileCheck -check-prefix CHECK-GENERIC-ARM %s
// RUN: %swift -typecheck %s -target x86_64-apple-macosx13.0 -target-cpu core2 -enable-experimental-feature TargetFeaturePredicate -parse-stdlib -Xcc -Xclang -Xcc -target-feature -Xcc -Xclang -Xcc +avx2 2>&1 | %FileCheck -check-prefix CHECK-CORE2-XCC-OVERRIDE %s

// REQUIRES: swift_feature_TargetFeaturePredicate

#if _hasTargetFeature("avx2")
#warning("has avx2")
#else
#warning("no avx2")
#endif

// A misspelled/unknown feature name is not a real feature
#if _hasTargetFeature("avx3000")
#warning("has avx3000")
#else
#warning("no avx3000")
#endif

#if arch(aarch64) && _hasTargetFeature("dotprod")
#warning("has dotprod")
#else
#warning("no dotprod")
#endif

// CHECK-HASWELL: has avx2
// CHECK-HASWELL: no avx3000
// CHECK-HASWELL: no dotprod

// CHECK-CORE2: no avx2
// CHECK-CORE2: no avx3000
// CHECK-CORE2: no dotprod

// CHECK-A14: no avx2
// CHECK-A14: no avx3000
// CHECK-A14: has dotprod

// CHECK-GENERIC-ARM: no avx2
// CHECK-GENERIC-ARM: no avx3000
// CHECK-GENERIC-ARM: no dotprod

// CHECK-CORE2-XCC-OVERRIDE: has avx2
// CHECK-CORE2-XCC-OVERRIDE: no avx3000
// CHECK-CORE2-XCC-OVERRIDE: no dotprod
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
// RUN: %target-typecheck-verify-swift

#if _hasTargetFeature("avx2") // expected-error {{invalid conditional compilation expression}}
#warning("has avx2")
#else
#warning("no avx2") // expected-warning {{no avx2}}
#endif
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
// RUN: %target-typecheck-verify-swift -enable-experimental-feature TargetFeaturePredicate

// REQUIRES: swift_feature_TargetFeaturePredicate

#if _hasTargetFeature(avx2) // expected-error {{'_hasTargetFeature' requires a single unlabeled argument for the target feature name}}
#endif

#if _hasTargetFeature("") // expected-error {{'_hasTargetFeature' requires a single unlabeled argument for the target feature name}}
#endif

#if _hasTargetFeature() // expected-error {{'_hasTargetFeature' requires a single unlabeled argument for the target feature name}}
#endif

#if _hasTargetFeature("avx2", "avx512f") // expected-error {{'_hasTargetFeature' requires a single unlabeled argument for the target feature name}}
#endif