Skip to content

Convert op

convert_op

CastInstrWithFlags

Bases: CastInstr

Source code in xdsl/backend/llvm/convert_op.py
class CastInstrWithFlags(instructions.CastInstr):
    # workaround: llvmlite's CastInstr doesn't support flags like 'trunc nsw' or 'zext nneg'
    def __init__(
        self,
        parent: LLVMBlock,
        op: str,
        val: Value,
        typ: Type,
        name: str = "",
        flags: tuple[str, ...] | list[str] = (),
    ):
        instructions.Instruction.__init__(
            self, parent, typ, op, [val], name=name, flags=flags
        )

    def descr(self, buf: list[str]) -> None:
        opname = " ".join((self.opname, *self.flags))
        op = self.operands[0]
        buf.append(
            f"{opname} {op.type} {op.get_reference()} to {self.type}{self._stringify_metadata(leading_comma=True)}\n"
        )

__init__(parent: LLVMBlock, op: str, val: Value, typ: Type, name: str = '', flags: tuple[str, ...] | list[str] = ())

Source code in xdsl/backend/llvm/convert_op.py
def __init__(
    self,
    parent: LLVMBlock,
    op: str,
    val: Value,
    typ: Type,
    name: str = "",
    flags: tuple[str, ...] | list[str] = (),
):
    instructions.Instruction.__init__(
        self, parent, typ, op, [val], name=name, flags=flags
    )

descr(buf: list[str]) -> None

Source code in xdsl/backend/llvm/convert_op.py
def descr(self, buf: list[str]) -> None:
    opname = " ".join((self.opname, *self.flags))
    op = self.operands[0]
    buf.append(
        f"{opname} {op.type} {op.get_reference()} to {self.type}{self._stringify_metadata(leading_comma=True)}\n"
    )

intrinsic_suffix(t: ir.Type) -> str

Return the LLVM intrinsic name suffix for a type, e.g. 'f32' or 'v4f32'.

Source code in xdsl/backend/llvm/convert_op.py
def intrinsic_suffix(t: ir.Type) -> str:
    """Return the LLVM intrinsic name suffix for a type, e.g. 'f32' or 'v4f32'."""
    if isinstance(t, ir.VectorType):
        assert isinstance(t.element, _FLOAT_TYPES)
        return f"v{t.count}{t.element.intrinsic_name}"
    assert isinstance(t, (ir.HalfType, ir.FloatType, ir.DoubleType, ir.IntType))
    return t.intrinsic_name

declare_intrinsic(module: ir.Module, name: str, ty: ir.Type, fnty: ir.FunctionType) -> ir.Function

Declare an LLVM intrinsic with a type-mangled name, reusing an existing declaration if present.

Source code in xdsl/backend/llvm/convert_op.py
def declare_intrinsic(
    module: ir.Module,
    name: str,
    ty: ir.Type,
    fnty: ir.FunctionType,
) -> ir.Function:
    """Declare an LLVM intrinsic with a type-mangled name, reusing an existing declaration if present."""
    full_name = f"{name}.{intrinsic_suffix(ty)}"
    if full_name in module.globals:
        return cast(ir.Function, module.globals[full_name])
    return ir.Function(module, fnty, name=full_name)

create_constant(result_type: Attribute, value: Attribute) -> ir.Constant

Source code in xdsl/backend/llvm/convert_op.py
def create_constant(result_type: Attribute, value: Attribute) -> ir.Constant:
    try:
        handler = _CONSTANT_VALUE_MAP[type(value)]
    except KeyError:
        raise LLVMTranslationException(
            f"Unsupported constant attribute type: {type(value)}"
        ) from None
    return ir.Constant(convert_type(result_type), handler(value))

convert_op(op: Operation, builder: ir.IRBuilder, val_map: dict[SSAValue, ir.Value], block_map: dict[Block, LLVMBlock] | None = None)

Convert an xDSL operation to an llvmlite LLVM IR.

Side effects

Mutates val_map by adding entries for the operation's results.

Parameters:

Name Type Description Default
op Operation

The xDSL operation to convert

required
builder IRBuilder

The LLVM IR builder for constructing instructions

required
val_map dict[SSAValue, Value]

The Mapping from xDSL SSA values to LLVM IR values. This dictionary is mutated to store the LLVM IR value produced by this operation for use by subsequent operations.

required

Raises:

Type Description
NotImplementedError

If the operation is not supported.

Source code in xdsl/backend/llvm/convert_op.py
def convert_op(
    op: Operation,
    builder: ir.IRBuilder,
    val_map: dict[SSAValue, ir.Value],
    block_map: dict[Block, LLVMBlock] | None = None,
):
    """
    Convert an xDSL operation to an llvmlite LLVM IR.

    Side effects:
        Mutates val_map by adding entries for the operation's results.

    Args:
        op: The xDSL operation to convert
        builder: The LLVM IR builder for constructing instructions
        val_map: The Mapping from xDSL SSA values to LLVM IR values.
                 This dictionary is mutated to store the LLVM IR value produced by this operation for
                 use by subsequent operations.

    Raises:
        NotImplementedError: If the operation is not supported.
    """
    match op:
        case op if type(op) in _BINARY_OP_MAP:
            _convert_binop(op, builder, val_map)
        case llvm.ICmpOp():
            _convert_icmp(op, builder, val_map)
        case llvm.FCmpOp():
            _convert_fcmp(op, builder, val_map)
        case op if type(op) in _CAST_OP_NAMES:
            _convert_cast(op, builder, val_map)
        case op if type(op) in _UNARY_INTRINSIC_MAP:
            _convert_unary_intrinsic(op, builder, val_map)
        case op if type(op) in _BINARY_INTRINSIC_MAP:
            _convert_binary_intrinsic(op, builder, val_map)
        case op if type(op) in _VECTOR_REDUCE_INTRINSIC_MAP:
            _convert_vector_reduce(op, builder, val_map)
        case llvm.FNegOp():
            _convert_fneg(op, builder, val_map)
        case llvm.CallOp():
            _convert_call(op, builder, val_map)
        case llvm.AllocaOp():
            _convert_alloca(op, builder, val_map)
        case llvm.LoadOp():
            _convert_load(op, builder, val_map)
        case llvm.StoreOp():
            _convert_store(op, builder, val_map)
        case llvm.ExtractValueOp():
            val_map[op.results[0]] = builder.extract_value(
                val_map[op.container], list(op.position.iter_values())
            )
        case llvm.InsertValueOp():
            val_map[op.results[0]] = builder.insert_value(
                val_map[op.container],
                val_map[op.value],
                list(op.position.iter_values()),
            )
        case llvm.GEPOp():
            _convert_getelementptr(op, builder, val_map)
        case llvm.InlineAsmOp():
            _convert_inline_asm(op, builder, val_map)
        case llvm.BrOp() if block_map is not None:
            _convert_br(op, builder, val_map, block_map)
        case llvm.CondBrOp() if block_map is not None:
            _convert_condbr(op, builder, val_map, block_map)
        case llvm.UnreachableOp():
            builder.unreachable()
        case llvm.SelectOp():
            _convert_select(op, builder, val_map)
        case llvm.MaskedStoreOp():
            _convert_masked_store(op, builder, val_map)
        case llvm.ReturnOp():
            _convert_return(op, builder, val_map)
        case llvm.ZeroOp():
            val_map[op.res] = ir.Constant(convert_type(op.res.type), None)
        case llvm.UndefOp():
            val_map[op.res] = ir.Constant(convert_type(op.res.type), ir.Undefined)
        case llvm.AddressOfOp():
            _convert_addressof(op, builder, val_map)
        case llvm.CallIntrinsicOp():
            _convert_call_intrinsic(op, builder, val_map)
        case llvm.InsertElementOp():
            val_map[op.res] = builder.insert_element(
                val_map[op.vector],
                val_map[op.value],
                val_map[op.index],
            )
        case llvm.ShuffleVectorOp():
            _convert_shuffle_vector(op, builder, val_map)
        case llvm.FMAOp():
            _convert_fma(op, builder, val_map)
        case llvm.ConstantOp():
            val_map[op.result] = create_constant(op.result.type, op.value)
        case _:
            raise NotImplementedError(f"Conversion not implemented for op: {op.name}")