/* Copyright 2025 The OpenXLA Authors.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/

#ifndef XLA_SERVICE_COLLECTIVE_PERMUTE_CYCLE_H_
#define XLA_SERVICE_COLLECTIVE_PERMUTE_CYCLE_H_

// Cycle manipulation on SourceTargetPairs in collective permute instructions.
#include <utility>

#include "xla/service/source_target_pairs.h"

namespace xla {
namespace collective_permute_cycle {
// TODO: b/388623407 - rename kUnknown to kNone
enum class CycleType { kNone, kForward, kBackward };

// Splits input into backward (first) and forwards (second) edges.
// In backward cycle, backwards edge is the first element and in forwards
// cycle, backward edge is the last element.
std::pair<SourceTargetPairs, SourceTargetPairs> SplitEdges(
    const SourceTargetPairs& pairs, CycleType cycle_type);

// Returns the cycle type of this source-target pairs.
// TODO: b/388623407 - remove assumptions that pairs are ordered and 0 based.
CycleType GetCycleType(const SourceTargetPairs& pairs);
bool IsForwardCycle(const SourceTargetPairs& pairs);
bool IsBackwardCycle(const SourceTargetPairs& pairs);
bool HasCycles(const SourceTargetPairs& pairs);

// Returns true if the (source, target) pairs form a forward cycle with all
// participants in the cycle, such as {{0,1},{1,2},{2,3},{3,0}}. We assume
// that the (source, target) pairs are ordered via increasing source IDs, as
// they are currently generated by SPMD partitioning.
bool IsForwardCycle(const SourceTargetPairs& backedge,
                    const SourceTargetPairs& others);

// Returns true if the (source, target) pairs form a backward cycle with all
// participants in the cycle, such as {{0,3},{1,0},{2,1},{3,2}}. We assume
// that the (source, target) pairs are ordered via increasing source IDs, as
// they are currently generated by SPMD partitioning.
bool IsBackwardCycle(const SourceTargetPairs& backedge,
                     const SourceTargetPairs& others);

}  // namespace collective_permute_cycle
}  // namespace xla

#endif  // XLA_SERVICE_COLLECTIVE_PERMUTE_CYCLE_H_
