8000 Fix super-linear LLVM compile time for counted_for with large loop state in the JIT. by copybara-service[bot] · Pull Request #5545 · google/xls · GitHub
[go: up one dir, main page]

Skip to content
Draft
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
77 changes: 77 additions & 0 deletions xls/interpreter/ir_evaluator_test_base.cc
Original file line number Diff line number Diff line change
Expand Up @@ -2281,6 +2281,83 @@ top fn main() -> bits[32] {
IsOkAndHolds(Value(UBits(expected, 32))));
}

// A counted_for whose loop state is a large tuple-wrapped array (far too big
// for a stack alloca in the JIT) updated at a dynamic index on each iteration.
// Exercises trip counts of zero, one, even and odd to cover all the ways the
// loop state can flow between the state buffers.
TEST_P(IrEvaluatorTestBase, InterpretCountedForLargeArrayState) {
constexpr int64_t kArraySize = 1000;
constexpr std::string_view ir_text = R"(
package test

fn body(i: bits[32], st: (bits[1], bits[64][$0]), idx: bits[32][$1]) -> (bits[1], bits[64][$0]) {
flag: bits[1] = tuple_index(st, index=0)
arr: bits[64][$0] = tuple_index(st, index=1)
element_index: bits[32] = array_index(idx, indices=[i])
old: bits[64] = array_index(arr, indices=[element_index])
i_ext: bits[64] = zero_ext(i, new_bit_count=64)
one: bits[64] = literal(value=1)
new_val: bits[64] = add(old, i_ext)
new_plus_one: bits[64] = add(new_val, one)
updated: bits[64][$0] = array_update(arr, new_plus_one, indices=[element_index])
not_flag: bits[1] = not(flag)
ret result: (bits[1], bits[64][$0]) = tuple(not_flag, updated)
}

top fn main(arr: bits[64][$0], idx: bits[32][$1]) -> (bits[1], bits[64][$0]) {
zero: bits[1] = literal(value=0)
init_state: (bits[1], bits[64][$0]) = tuple(zero, arr)
ret counted_for.1: (bits[1], bits[64][$0]) = counted_for(init_state, trip_count=$2, stride=1, body=body, invariant_args=[idx])
}
)";
for (int64_t trip_count : {0, 1, 2, 7, 8}) {
// The IR requires a non-empty index array so always allocate at least one
// element.
const int64_t idx_size = std::max<int64_t>(trip_count, 1);
std::string formatted_ir =
absl::Substitute(ir_text, kArraySize, idx_size, trip_count);
XLS_ASSERT_OK_AND_ASSIGN(std::unique_ptr<Package> package,
Parser::ParsePackage(formatted_ir));
XLS_ASSERT_OK(VerifyPackage(package.get()));
XLS_ASSERT_OK_AND_ASSIGN(Function * function, package->GetTopAsFunction());

std::vector<uint64_t> expected_array(kArraySize, 0);
std::vector<Value> initial_elements;
initial_elements.reserve(kArraySize);
for (int64_t i = 0; i < kArraySize; ++i) {
initial_elements.push_back(Value(UBits(i, 64)));
expected_array[i] = i;
}
// Repeatedly write a handful of distinct indices (including one repeated
// index) so that the state carried between iterations matters.
std::vector<Value> index_elements;
index_elements.reserve(idx_size);
for (int64_t i = 0; i < idx_size; ++i) {
int64_t index = (i % 2 == 0) ? 17 : (kArraySize - 1 - i);
index_elements.push_back(Value(UBits(index, 32)));
if (i < trip_count) {
expected_array[index] += i + 1;
}
}
std::vector<Value> expected_elements;
expected_elements.reserve(kArraySize);
for (uint64_t element : expected_array) {
expected_elements.push_back(Value(UBits(element, 64)));
}

XLS_ASSERT_OK_AND_ASSIGN(Value initial_array,
Value::Array(initial_elements));
XLS_ASSERT_OK_AND_ASSIGN(Value index_array, Value::Array(index_elements));
XLS_ASSERT_OK_AND_ASSIGN(Value expected_array_value,
Value::Array(expected_elements));
Value expected =
Value::Tuple({Value(UBits(trip_count % 2, 1)), expected_array_value});
EXPECT_THAT(RunWithNoEvents(function, {initial_array, index_array}),
IsOkAndHolds(expected))
<< "trip_count = " << trip_count;
}
}

TEST_P(IrEvaluatorTestBase, InterpretTuple) {
Package package("my_package");
XLS_ASSERT_OK_AND_ASSIGN(Function * function,
Expand Down
79 changes: 52 additions & 27 deletions xls/jit/ir_builder_visitor.cc
Original file line number Diff line number Diff line change
Expand Up @@ -2260,21 +2260,44 @@ absl::Status IrBuilderVisitor::HandleCountedFor(CountedFor* counted_for) {
counted_for->invariant_args().size())),
/*include_wrapper_args=*/true));
XLS_ASSIGN_OR_RETURN(llvm::Function * body, GetFunction(counted_for->body()));
llvm::IRBuilder<>& b = node_context.entry_builder();

// Create a buffer to hold the loop state and write in the initial value.
// The loop state is held in two buffers which are ping-ponged between
// iterations: the body function reads the state from one buffer and writes
// the next state into the other. The buffer pointers are carried across
// iterations as loop-carried values (phis) and swapped on every iteration so
// that no copy of the state is required between iterations.
//
// Note: the state is only ever moved around with memcpy, never as an LLVM
// first-class aggregate value (load/store of the whole state type). LLVM
// scalarizes aggregate loads/stores of small-ish arrays and all structs
// element-by-element (InstCombine, SROA) which results in super-linear
// compile time and memory usage for large array-typed loop states.
llvm::Type* state_type = type_converter()->ConvertToLlvmType(
counted_for->initial_value()->GetType());
AllocaBuffer loop_state_buffer = node_context.CreateAlloca(state_type);
node_context.entry_builder().CreateStore(node_context.LoadOperand(0),
loop_state_buffer.value());
int64_t state_size = type_converter()->GetTypeByteSize(
counted_for->initial_value()->GetType());
AllocaBuffer state_buffer_a = node_context.CreateAlloca(state_type);
AllocaBuffer state_buffer_b = node_context.CreateAlloca(state_type);
LlvmMemcpy(state_buffer_a.value(), node_context.GetOperandPtr(0), state_size,
b);

std::vector<llvm::Value*> invariant_arg_buffers;
for (int64_t i = 1; i < counted_for->operand_count(); ++i) {
invariant_arg_buffers.push_back(node_context.GetOperandPtr(i));
}

LlvmIrLoop loop(counted_for->trip_count(), node_context.entry_builder(),
counted_for->stride());
constexpr std::string_view kStateBufferName = "state_buffer";
constexpr std::string_view kNextStateBufferName = "next_state_buffer";
LlvmIrLoop loop(
counted_for->trip_count(), b, counted_for->stride(),
/*insert_before=*/nullptr,
{LoopCarriedValue{std::string(kStateBufferName), state_buffer_a.value()},
LoopCarriedValue{std::string(kNextStateBufferName),
state_buffer_b.value()}});
llvm::Value* state_buffer = loop.GetLoopCarriedValue(kStateBufferName);
llvm::Value* next_state_buffer =
loop.GetLoopCarriedValue(kNextStateBufferName);

llvm::Type* index_type = type_converter()->ConvertToLlvmType(
counted_for->body()->param(0)->GetType());
Expand All @@ -2291,33 +2314,35 @@ absl::Status IrBuilderVisitor::HandleCountedFor(CountedFor* counted_for) {
// InvT_0 invariant_arg_0, ... , InvT_n invariant_arg_n)
std::vector<llvm::Value*> input_arg_ptrs;
input_arg_ptrs.push_back(index_buffer.value());
input_arg_ptrs.push_back(loop_state_buffer.value());
input_arg_ptrs.push_back(state_buffer);
input_arg_ptrs.insert(input_arg_ptrs.end(), invariant_arg_buffers.begin(),
invariant_arg_buffers.end());

AllocaBuffer next_state_buffer =
node_context.CreateAlloca(loop.body_builder(), state_type);
XLS_RETURN_IF_ERROR(
CallFunction(body, input_arg_ptrs, {next_state_buffer.value()},
node_context.GetTempBufferArg(),
node_context.GetInterpreterEventsArg(),
node_context.GetInstanceContextArg(),
node_context.GetJitRuntimeArg(), loop.body_builder())
.status());
XLS_RETURN_IF_ERROR(CallFunction(body, input_arg_ptrs, {next_state_buffer},
node_context.GetTempBufferArg(),
node_context.GetInterpreterEventsArg(),
node_context.GetInstanceContextArg(),
node_context.GetJitRuntimeArg(),
loop.body_builder())
.status());
index_buffer.CleanUp(loop.body_builder());
// TODO(meheff): 2022/09/09 Rather than loading the state and storing it in
// the state buffer for the next iteration, simply swap the state and
// next-state buffer pointers passed to the loop body function.
llvm::Value* next_state =
loop.body_builder().CreateLoad(state_type, next_state_buffer.value());
loop.body_builder().CreateStore(next_state, loop_state_buffer.value());
next_state_buffer.CleanUp(loop.body_builder());

loop.Finalize();
// Swap the buffers for the next iteration.
loop.Finalize(/*final_body_block_builder=*/std::nullopt,
{{std::string(kStateBufferName), next_state_buffer},
{std::string(kNextStateBufferName), state_buffer}});

return FinalizeNodeIrContextWithAllocaValue(std::move(node_context),
std::move(loop_state_buffer),
&loop.exit_builder());
// After the loop exits, the final state is in `state_buffer` (which is
// defined in the preheader and thus available in the exit block). Copy it to
// the output and release both buffers.
node_context.FinalizeWithPointerToValue(
state_buffer, loop.exit_builder(), /*return_value=*/std::nullopt,
/*result_type=*/std::nullopt, [&](llvm::IRBuilder<>& pre_ret) {
state_buffer_a.CleanUp(pre_ret);
state_buffer_b.CleanUp(pre_ret);
});
node_context_.emplace(std::move(node_context));
return absl::OkStatus();
}

absl::Status IrBuilderVisitor::HandleCover(Cover* cover) {
Expand Down
Loading
0