Skip to content

Commit

Permalink
[utils] Utility functions from rocket-chip
Browse files Browse the repository at this point in the history
  • Loading branch information
OceanS2000 committed Feb 15, 2023
1 parent abe2957 commit 41a1de8
Show file tree
Hide file tree
Showing 2 changed files with 54 additions and 0 deletions.
19 changes: 19 additions & 0 deletions tilelink/src/utils/OH1.scala
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
// SPDX-License-Identifier: Apache-2.0
// Copyright 2016-2017 SiFive, Inc. See LICENSE.SiFive for details

package utils

import chisel3._
import chisel3.util.{Cat, OHToUInt}

object OH1 {
def OH1ToOH(x: UInt): UInt =
((x << 1).asUInt | 1.U) & (~Cat(0.U(1.W), x)).asUInt

def OH1ToUInt(x: UInt): UInt = OHToUInt(OH1ToOH(x))

def UIntToOH1(x: UInt, width: Int): UInt =
(~((-1).S(width.W).asUInt << x)(width - 1, 0)).asUInt

def UIntToOH1(x: UInt): UInt = UIntToOH1(x, (1 << x.getWidth) - 1)
}
35 changes: 35 additions & 0 deletions tilelink/src/utils/package.scala
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
// SPDX-License-Identifier: Apache-2.0
// Copyright 2016-2017 SiFive, Inc. See LICENSE.SiFive for details

import chisel3._

import scala.annotation.tailrec
import scala.math.min

package object utils {
// Fill 1s from low bits to high bits
def leftOR(x: UInt): UInt = leftOR(x, x.getWidth, x.getWidth)

def leftOR(x: UInt, width: Integer, cap: Integer = 999999): UInt = {
val stop = min(width, cap)

@tailrec
def helper(s: Int, x: UInt): UInt =
if (s >= stop) x else helper(s + s, x | (x << s)(width - 1, 0))

helper(1, x)(width - 1, 0)
}

// Fill 1s form high bits to low bits
def rightOR(x: UInt): UInt = rightOR(x, x.getWidth, x.getWidth)

def rightOR(x: UInt, width: Integer, cap: Integer = 999999): UInt = {
val stop = min(width, cap)

@tailrec
def helper(s: Int, x: UInt): UInt =
if (s >= stop) x else helper(s + s, x | (x >> s)(width - 1, 0))

helper(1, x)(width - 1, 0)
}
}

0 comments on commit 41a1de8

Please sign in to comment.