duskphantom_middle/ir/
operand.rs

1// Copyright 2024 Duskphantom Authors
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14//
15// SPDX-License-Identifier: Apache-2.0
16
17use super::*;
18
19#[derive(Clone, PartialEq, Eq, Hash, Debug)]
20pub enum Operand {
21    Constant(Constant),
22    Global(GlobalPtr),
23    Parameter(ParaPtr),
24    Instruction(InstPtr),
25}
26
27impl Display for Operand {
28    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
29        match self {
30            Operand::Constant(c) => write!(f, "{}", c),
31            Operand::Global(g) => write!(f, "{}", g),
32            Operand::Parameter(p) => write!(f, "{}", p),
33            Operand::Instruction(inst) => write!(f, "{}", inst),
34        }
35    }
36}
37
38impl Operand {
39    pub fn get_type(&self) -> ValueType {
40        match self {
41            Operand::Constant(c) => c.get_type(),
42            // Type of global var identifier (@gvar) is pointer
43            Operand::Global(g) => ValueType::Pointer(g.as_ref().value_type.clone().into()),
44            Operand::Parameter(p) => p.as_ref().value_type.clone(),
45            Operand::Instruction(inst) => inst.get_value_type(),
46        }
47    }
48}
49
50impl From<Constant> for Operand {
51    fn from(c: Constant) -> Self {
52        Self::Constant(c)
53    }
54}
55
56impl From<InstPtr> for Operand {
57    fn from(inst: InstPtr) -> Self {
58        Self::Instruction(inst)
59    }
60}
61
62impl From<ParaPtr> for Operand {
63    fn from(param: ParaPtr) -> Self {
64        Self::Parameter(param)
65    }
66}
67
68impl From<GlobalPtr> for Operand {
69    fn from(gvar: GlobalPtr) -> Self {
70        Self::Global(gvar)
71    }
72}
73
74impl Operand {
75    pub fn is_const(&self) -> bool {
76        matches!(self, Operand::Constant(_))
77    }
78}