Skip to content

Commit 78a7887

Browse files
committed
SILCombine: optimize mark_dependence of a string literal.
This pattern can occur after StringOptimization when a utf8CString of a literal is replace by the string_literal itself.
1 parent f6c0305 commit 78a7887

File tree

2 files changed

+33
-0
lines changed

2 files changed

+33
-0
lines changed

lib/SILOptimizer/SILCombiner/SILCombinerMiscVisitors.cpp

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2181,6 +2181,18 @@ visitAllocRefDynamicInst(AllocRefDynamicInst *ARDI) {
21812181
return NewInst;
21822182
}
21832183

2184+
/// Returns true if \p val is a literal instruction or a struct of a literal
2185+
/// instruction.
2186+
/// What we want to catch here is a UnsafePointer<Int8> of a string literal.
2187+
static bool isLiteral(SILValue val) {
2188+
while (auto *str = dyn_cast<StructInst>(val)) {
2189+
if (str->getNumOperands() != 1)
2190+
return false;
2191+
val = str->getOperand(0);
2192+
}
2193+
return isa<LiteralInst>(val);
2194+
}
2195+
21842196
SILInstruction *SILCombiner::visitMarkDependenceInst(MarkDependenceInst *mdi) {
21852197
auto base = lookThroughOwnershipInsts(mdi->getBase());
21862198

@@ -2242,6 +2254,14 @@ SILInstruction *SILCombiner::visitMarkDependenceInst(MarkDependenceInst *mdi) {
22422254
}
22432255
}
22442256
}
2257+
2258+
if (isLiteral(mdi->getValue())) {
2259+
// A literal lives forever, so no mark_dependence is needed.
2260+
// This pattern can occur after StringOptimization when a utf8CString of
2261+
// a literal is replace by the string_literal itself.
2262+
replaceInstUsesWith(*mdi, mdi->getValue());
2263+
return eraseInstFromFunction(*mdi);
2264+
}
22452265

22462266
return nullptr;
22472267
}

test/SILOptimizer/sil_combine_ossa.sil

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4195,6 +4195,19 @@ bb0(%0 : $*Builtin.Int64, %1 : @owned $B):
41954195
return %4 : $Builtin.Int64
41964196
}
41974197

4198+
// CHECK-LABEL: sil [ossa] @mark_dependence_string_literal
4199+
// CHECK: %1 = string_literal utf8 "a"
4200+
// CHECK: %2 = struct $UnsafePointer<Int8> (%1 : $Builtin.RawPointer)
4201+
// CHECK: return %2
4202+
// CHECK: } // end sil function 'mark_dependence_string_literal'
4203+
sil [ossa] @mark_dependence_string_literal : $@convention(thin) (@guaranteed Builtin.NativeObject) -> UnsafePointer<Int8> {
4204+
bb0(%0 : @guaranteed $Builtin.NativeObject):
4205+
%1 = string_literal utf8 "a"
4206+
%2 = struct $UnsafePointer<Int8> (%1 : $Builtin.RawPointer)
4207+
%3 = mark_dependence %2 : $UnsafePointer<Int8> on %0 : $Builtin.NativeObject
4208+
return %3 : $UnsafePointer<Int8>
4209+
}
4210+
41984211
// Test to see if we can constant fold a classify_bridge_object on a Swift class
41994212
// to false.
42004213
// CHECK-LABEL: sil [ossa] @test_classify_fold :

0 commit comments

Comments
 (0)