[llvm] [HotColdSplit] Protect Swift once-initialization functions from splitting (PR #179002)
via llvm-commits
llvm-commits at lists.llvm.org
Fri Jan 30 20:30:02 PST 2026
https://github.com/SharonXSharon updated https://github.com/llvm/llvm-project/pull/179002
>From 2694bebd8758bef1de27e5a70789e68f8d6146f9 Mon Sep 17 00:00:00 2001
From: Sharon Xu <sharonxu at fb.com>
Date: Fri, 30 Jan 2026 16:08:47 -0800
Subject: [PATCH] [HotColdSplit] Protect Swift once-initialization functions
from splitting
Swift uses atomic once-tokens for thread-safe lazy initialization of static
variables. The once-wrapper functions (_WZ suffix) implement this pattern:
if (once_token == initialized) return cached_value; // hot path
swift_once(&token, init); // cold path
return cached_value;
Before Hot/Cold Splitting (correct):
define double @"$s...value_WZ"() {
entry:
%token = load atomic i64, ptr @once_token seq_cst
%initialized = icmp eq i64 %token, -1
br i1 %initialized, label %already_init, label %need_init
need_init: ; cold path - executed once
call void @swift_once(ptr @once_token, ptr @initializer)
; ... initialization logic ...
br label %already_init
already_init:
%cached = load double, ptr @cached_value
ret double %cached
}
After Hot/Cold Splitting (broken):
define double @"$s...value_WZ"() {
entry:
%token = load atomic i64, ptr @once_token seq_cst
%initialized = icmp eq i64 %token, -1
br i1 %initialized, label %already_init, label %codeRepl
codeRepl:
call void @"$s...value_WZ.cold.1"() ; <-- cold path extracted
br label %already_init
already_init:
%cached = load double, ptr @cached_value
ret double %cached
}
define internal void @"$s...value_WZ.cold.1"() cold {
call void @swift_once(ptr @once_token, ptr @initializer)
; ... initialization logic ...
ret void
}
The Problem:
Hot/Cold Splitting identifies need_init as cold (executed once during program
lifetime) and extracts it into a separate .cold function. This breaks semantics.
This change adds two levels of protection:
1. Function-level: Detect Swift once-wrapper functions by their mangled name
pattern (_WZ, _Wz suffix) and skip them entirely.
2. Block-level: Detect blocks containing swift_once/dispatch_once calls and
prevent their extraction.
Swift mangling patterns covered (from lldb/source/Core/Mangled.cpp):
- Swift 4.2: $S, _$S
- Swift 5+: $s, _$s
- Embedded Swift: $e, _$e
- Old style: _TtC, _TtGC, _TtP
---
llvm/lib/Transforms/IPO/HotColdSplitting.cpp | 126 ++++++++++++++++--
.../HotColdSplit/swift-once-wrapper.ll | 115 ++++++++++++++++
2 files changed, 232 insertions(+), 9 deletions(-)
create mode 100644 llvm/test/Transforms/HotColdSplit/swift-once-wrapper.ll
diff --git a/llvm/lib/Transforms/IPO/HotColdSplitting.cpp b/llvm/lib/Transforms/IPO/HotColdSplitting.cpp
index 3d8b7cbb59630..ddf866c311deb 100644
--- a/llvm/lib/Transforms/IPO/HotColdSplitting.cpp
+++ b/llvm/lib/Transforms/IPO/HotColdSplitting.cpp
@@ -61,6 +61,8 @@
STATISTIC(NumColdRegionsFound, "Number of cold regions found.");
STATISTIC(NumColdRegionsOutlined, "Number of cold regions outlined.");
+STATISTIC(NumSwiftOnceSkipped,
+ "Number of Swift once-initialization functions skipped.");
using namespace llvm;
@@ -87,12 +89,103 @@ static cl::opt<int> MaxParametersForSplit(
"hotcoldsplit-max-params", cl::init(4), cl::Hidden,
cl::desc("Maximum number of parameters for a split function"));
-static cl::opt<int> ColdBranchProbDenom(
- "hotcoldsplit-cold-probability-denom", cl::init(100), cl::Hidden,
- cl::desc("Divisor of cold branch probability."
- "BranchProbability = 1/ColdBranchProbDenom"));
+static cl::opt<int>
+ ColdBranchProbDenom("hotcoldsplit-cold-probability-denom", cl::init(100),
+ cl::Hidden,
+ cl::desc("Divisor of cold branch probability."
+ "BranchProbability = 1/ColdBranchProbDenom"));
namespace {
+
+//===----------------------------------------------------------------------===//
+// Swift Once-Initialization Protection
+//===----------------------------------------------------------------------===//
+//
+// Swift uses atomic once-tokens for thread-safe lazy initialization of static
+// variables. The pattern looks like:
+//
+// if (once_token == initialized) {
+// return cached_value; // hot path
+// }
+// swift_once(&token, init); // cold path - only executed once
+// return cached_value;
+//
+// Hot/Cold Splitting can break this pattern by extracting the cold path into
+// a separate function, which corrupts the atomicity guarantees.
+//
+// Two levels of protection/detection is needed:
+//
+// 1. FUNCTION-LEVEL (isSwiftOnceWrapper):
+// Detects Swift once-wrapper functions by their mangled name (_WZ suffix),
+// works even if swift_once was inlined
+//
+// 2. BLOCK-LEVEL (containsSwiftOnceCall):
+// - Detects blocks containing swift_once/dispatch_once calls and skip
+// splitting
+// - Safety net for:
+// a) Objective-C code using dispatch_once
+// b) Swift code manually calling swift_once outside _WZ functions
+// c) Any other atomic initialization patterns
+//
+//===----------------------------------------------------------------------===//
+
+bool isSwiftOnceWrapper(const Function &F) {
+ StringRef Name = F.getName();
+
+ // Check for Swift mangled names:
+ // Swift 4.2: $S, _$S
+ // Swift 5+: $s, _$s
+ // Embedded Swift: $e, _$e
+ // Old style: _TtC, _TtGC, _TtP
+ bool IsSwiftMangled = Name.starts_with("_$s") || Name.starts_with("$s") ||
+ Name.starts_with("_$S") || Name.starts_with("$S") ||
+ Name.starts_with("_$e") || Name.starts_with("$e") ||
+ Name.starts_with("_TtC") || Name.starts_with("_TtGC") ||
+ Name.starts_with("_TtP");
+
+ if (!IsSwiftMangled)
+ return false;
+
+ // Check for once-wrapper patterns in Swift mangled names:
+ // _WZ: one-time initialization function (once wrapper)
+ // _Wz: one-time initialization helper
+ // These may be followed by LLVM suffixes like ".llvm.123456" or ".Tgm"
+ if (Name.ends_with("_WZ") || Name.ends_with("_Wz"))
+ return true;
+
+ // Check for _WZ or _Wz followed by a dot (LLVM suffix)
+ if (Name.contains("_WZ.") || Name.contains("_Wz."))
+ return true;
+
+ // Also check for type metadata accessor patterns that use once tokens
+ // These have patterns like "Ma" (metadata accessor) in the mangled name
+ // and internally call swift_once
+ if (Name.contains("Ma") && Name.contains("_T"))
+ return true;
+
+ return false;
+}
+
+/// Check if a basic block contains a call to swift_once or similar
+/// atomic initialization functions that should not be split.
+bool containsSwiftOnceCall(const BasicBlock &BB) {
+ for (const Instruction &I : BB) {
+ if (auto *CB = dyn_cast<CallBase>(&I)) {
+ if (Function *Callee = CB->getCalledFunction()) {
+ StringRef Name = Callee->getName();
+ // swift_once: Swift's once-initialization runtime function
+ // dispatch_once: libdispatch once function (also used by Swift)
+ // dispatch_once_f: function pointer variant
+ if (Name == "swift_once" || Name == "dispatch_once" ||
+ Name == "dispatch_once_f" || Name == "_dispatch_once" ||
+ Name == "_swift_once")
+ return true;
+ }
+ }
+ }
+ return false;
+}
+
// Same as blockEndsInUnreachable in CodeGen/BranchFolding.cpp. Do not modify
// this function unless you modify the MBB version as well.
//
@@ -108,8 +201,7 @@ bool blockEndsInUnreachable(const BasicBlock &BB) {
return !(isa<ReturnInst>(I) || isa<IndirectBrInst>(I));
}
-void analyzeProfMetadata(BasicBlock *BB,
- BranchProbability ColdProbThresh,
+void analyzeProfMetadata(BasicBlock *BB, BranchProbability ColdProbThresh,
SmallPtrSetImpl<BasicBlock *> &AnnotatedColdBlocks) {
// TODO: Handle branches with > 2 successors.
BranchInst *CondBr = dyn_cast<BranchInst>(BB->getTerminator());
@@ -185,6 +277,13 @@ static bool mayExtractBlock(const BasicBlock &BB) {
return false;
}
+ // Do not extract blocks containing swift_once or dispatch_once calls.
+ if (containsSwiftOnceCall(BB)) {
+ LLVM_DEBUG(dbgs() << "Block contains swift_once/dispatch_once call, "
+ << "not extracting\n");
+ return false;
+ }
+
return true;
}
@@ -237,7 +336,8 @@ bool HotColdSplitting::isBasicBlockCold(
if (PSI->isColdBlock(BB, BFI))
return true;
} else {
- // Find cold blocks of successors of BB during a reverse postorder traversal.
+ // Find cold blocks of successors of BB during a reverse postorder
+ // traversal.
analyzeProfMetadata(BB, ColdProbThresh, AnnotatedColdBlocks);
// A statically cold BB would be known before it is visited
@@ -277,6 +377,14 @@ bool HotColdSplitting::shouldOutlineFrom(const Function &F) const {
if (isScopedEHPersonality(classifyEHPersonality(F.getPersonalityFn())))
return false;
+ // Do not outline Swift once-initialization wrapper functions.
+ if (isSwiftOnceWrapper(F)) {
+ LLVM_DEBUG(dbgs() << "Skipping Swift once-wrapper function: " << F.getName()
+ << "\n");
+ ++NumSwiftOnceSkipped;
+ return false;
+ }
+
return true;
}
@@ -802,8 +910,8 @@ bool HotColdSplitting::run(Module &M) {
return Changed;
}
-PreservedAnalyses
-HotColdSplittingPass::run(Module &M, ModuleAnalysisManager &AM) {
+PreservedAnalyses HotColdSplittingPass::run(Module &M,
+ ModuleAnalysisManager &AM) {
auto &FAM = AM.getResult<FunctionAnalysisManagerModuleProxy>(M).getManager();
auto LookupAC = [&FAM](Function &F) -> AssumptionCache * {
diff --git a/llvm/test/Transforms/HotColdSplit/swift-once-wrapper.ll b/llvm/test/Transforms/HotColdSplit/swift-once-wrapper.ll
new file mode 100644
index 0000000000000..f671db5285ade
--- /dev/null
+++ b/llvm/test/Transforms/HotColdSplit/swift-once-wrapper.ll
@@ -0,0 +1,115 @@
+; RUN: opt -passes=hotcoldsplit -hotcoldsplit-threshold=0 -S < %s | FileCheck %s
+
+target datalayout = "e-m:o-i64:64-f80:128-n8:16:32:64-S128"
+target triple = "arm64-apple-ios14.0"
+
+; Test that Swift once-wrapper functions (_WZ suffix) are not split.
+; These functions implement thread-safe lazy initialization of static variables
+; using atomic once-tokens. Splitting them can break the atomicity.
+
+ at once_token = internal global i64 0
+ at cached_value = internal global double 0.0
+
+; Swift once-wrapper function - should NOT be split even though it has cold blocks
+; CHECK-NOT: @"$s15QuickLayoutCore11ScreenScaleV5value_WZ{{.*}}.cold
+; CHECK-LABEL: define {{.*}}@"$s15QuickLayoutCore11ScreenScaleV5value_WZ"(
+; CHECK: call void @swift_once
+; CHECK: ret double
+define double @"$s15QuickLayoutCore11ScreenScaleV5value_WZ"() {
+entry:
+ %token = load atomic i64, ptr @once_token seq_cst, align 8
+ %initialized = icmp eq i64 %token, -1
+ br i1 %initialized, label %already_init, label %need_init
+
+need_init:
+ ; Cold path with unreachable - normally would be split
+ call void @swift_once(ptr @once_token, ptr @init_screen_scale)
+ call void @expensive_computation()
+ call void @sink()
+ unreachable
+
+already_init:
+ %cached = load double, ptr @cached_value, align 8
+ ret double %cached
+}
+
+; Swift once-wrapper with LLVM suffix - should also NOT be split
+; CHECK-NOT: @"$s24IGPremainStartupAnalyzerAAC6shared_WZ{{.*}}.cold
+; CHECK-LABEL: define {{.*}}@"$s24IGPremainStartupAnalyzerAAC6shared_WZ.llvm.5439742213303041064"(
+define ptr @"$s24IGPremainStartupAnalyzerAAC6shared_WZ.llvm.5439742213303041064"() {
+entry:
+ %token = load atomic i64, ptr @once_token seq_cst, align 8
+ %initialized = icmp eq i64 %token, -1
+ br i1 %initialized, label %already_init, label %need_init
+
+need_init:
+ call void @swift_once(ptr @once_token, ptr @init_screen_scale)
+ call void @sink()
+ unreachable
+
+already_init:
+ %cached = load ptr, ptr @cached_value, align 8
+ ret ptr %cached
+}
+
+; Regular Swift function (not _WZ) - CAN be split
+; CHECK-LABEL: define {{.*}}@"$s15QuickLayoutCore10otherFuncyyF"(
+; CHECK: call {{.*}}@"$s15QuickLayoutCore10otherFuncyyF.cold
+define void @"$s15QuickLayoutCore10otherFuncyyF"(i32 %cond) {
+entry:
+ %is_cold = icmp eq i32 %cond, 0
+ br i1 %is_cold, label %cold_path, label %hot_path
+
+cold_path:
+ call void @expensive_computation()
+ call void @another_expensive_call()
+ call void @sink()
+ unreachable
+
+hot_path:
+ ret void
+}
+
+; Test swift_once call in a non-_WZ function - block should not be extracted
+; The function itself can be considered for splitting, but the block with
+; swift_once should not be extracted
+; CHECK-NOT: @test_swift_once_in_block{{.*}}.cold
+; CHECK-LABEL: define {{.*}}@test_swift_once_in_block(
+define void @test_swift_once_in_block(i32 %cond) {
+entry:
+ %is_cold = icmp eq i32 %cond, 0
+ br i1 %is_cold, label %init_block, label %hot_path
+
+init_block:
+ ; This block calls swift_once and should not be extracted
+ call void @swift_once(ptr @once_token, ptr @init_screen_scale)
+ call void @sink()
+ unreachable
+
+hot_path:
+ ret void
+}
+
+; Test dispatch_once - block should not be extracted
+; CHECK-NOT: @test_dispatch_once{{.*}}.cold
+; CHECK-LABEL: define {{.*}}@test_dispatch_once(
+define void @test_dispatch_once(i32 %cond) {
+entry:
+ %is_cold = icmp eq i32 %cond, 0
+ br i1 %is_cold, label %init_block, label %hot_path
+
+init_block:
+ call void @dispatch_once(ptr @once_token, ptr @init_screen_scale)
+ call void @sink()
+ unreachable
+
+hot_path:
+ ret void
+}
+
+declare void @swift_once(ptr, ptr)
+declare void @dispatch_once(ptr, ptr)
+declare void @init_screen_scale()
+declare void @expensive_computation()
+declare void @another_expensive_call()
+declare void @sink() cold
More information about the llvm-commits
mailing list