Skip to content

ArrayElementValuePropagation: require that the initialization and element-get are in the same block for non-trivial values. #77610

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Nov 15, 2024
Merged
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
11 changes: 11 additions & 0 deletions lib/SILOptimizer/Transforms/ArrayElementValuePropagation.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -244,6 +244,17 @@ bool ArrayAllocation::replaceGetElements() {
if (EltValueIt == ElementValueMap.end())
continue;

SILValue element = EltValueIt->second;

// In OSSA we only insert a copy_value of the element at the array initialization
// point. This would result in an over-consume if the getElement is in a loop.
// Therefore require that both semantic calls are in the same block.
if (ArrayValue->getFunction()->hasOwnership() &&
!element->getType().isTrivial(ArrayValue->getFunction()) &&
ArrayValue->getParentBlock() != GetElementCall->getParent()) {
continue;
}

Changed |= GetElement.replaceByValue(EltValueIt->second);
}
return Changed;
Expand Down
17 changes: 17 additions & 0 deletions test/SILOptimizer/array_element_propagation_crash.swift
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,24 @@ func testit(_ arr: inout [Int]) {
var a = [27]
testit(&a)

// Second test case:
var gg = ""

@inline(never)
func use(_ s: String) {
gg = s
}

func testLoop() {
let a = [""]

for _ in 0..<1000 {
use(a[0])
}
}

// As a bonus, also check if the code works as expected.
// CHECK: [27, 28]
print(a)

testLoop()