Skip to main content

qirc/
ast.rs

1use crate::diag::Span;
2
3#[derive(Clone, PartialEq, Debug)]
4pub enum Ty {
5    Void,
6    Int(u32),
7    Half,
8    Float,
9    Double,
10    X86Fp80,
11    Fp128,
12    Ptr(Option<Box<Ty>>),
13    Array(u64, Box<Ty>),
14    Vector {
15        len: u64,
16        scalable: bool,
17        elem: Box<Ty>,
18    },
19    Struct {
20        fields: Vec<Ty>,
21        packed: bool,
22    },
23    Named(String),
24    Func {
25        ret: Box<Ty>,
26        params: Vec<Ty>,
27        varargs: bool,
28    },
29    Label,
30    Metadata,
31    Token,
32    Opaque,
33}
34
35impl Ty {
36    pub fn pointee_name(&self) -> Option<&str> {
37        match self {
38            Ty::Ptr(Some(inner)) => match inner.as_ref() {
39                Ty::Named(name) => Some(name),
40                _ => None,
41            },
42            _ => None,
43        }
44    }
45}
46
47#[derive(Clone, PartialEq, Debug)]
48pub enum Value {
49    Local(String),
50    Global(String),
51    Int(i128),
52    Float(f64),
53    Bool(bool),
54    Null,
55    NoneValue,
56    Undef,
57    Poison,
58    ZeroInit,
59    Bytes(Vec<u8>),
60    Aggregate(Vec<TypedValue>),
61    ConstExpr(Box<ConstExpr>),
62    MetadataRef(String),
63    MetadataString(String),
64    BlockAddress,
65}
66
67#[derive(Clone, PartialEq, Debug)]
68pub struct TypedValue {
69    pub ty: Ty,
70    pub value: Value,
71    pub span: Span,
72}
73
74#[derive(Clone, PartialEq, Debug)]
75pub enum ConstExpr {
76    Cast {
77        op: CastOp,
78        operand: TypedValue,
79        to: Ty,
80    },
81    GetElementPtr {
82        inbounds: bool,
83        base_ty: Ty,
84        ptr: TypedValue,
85        indices: Vec<TypedValue>,
86    },
87    Binary {
88        op: BinOp,
89        lhs: TypedValue,
90        rhs: TypedValue,
91    },
92}
93
94macro_rules! keywords {
95    ($name:ident { $($variant:ident = $text:literal),* $(,)? }) => {
96        #[derive(Clone, Copy, PartialEq, Eq, Debug)]
97        pub enum $name {
98            $($variant),*
99        }
100
101        impl $name {
102            pub fn from_keyword(keyword: &str) -> Option<$name> {
103                match keyword {
104                    $($text => Some($name::$variant),)*
105                    _ => None,
106                }
107            }
108
109            pub fn keyword(self) -> &'static str {
110                match self {
111                    $($name::$variant => $text),*
112                }
113            }
114        }
115    };
116}
117
118keywords!(BinOp {
119    Add = "add",
120    Sub = "sub",
121    Mul = "mul",
122    UDiv = "udiv",
123    SDiv = "sdiv",
124    URem = "urem",
125    SRem = "srem",
126    Shl = "shl",
127    LShr = "lshr",
128    AShr = "ashr",
129    And = "and",
130    Or = "or",
131    Xor = "xor",
132    FAdd = "fadd",
133    FSub = "fsub",
134    FMul = "fmul",
135    FDiv = "fdiv",
136    FRem = "frem",
137});
138
139impl BinOp {
140    pub fn is_float(self) -> bool {
141        matches!(
142            self,
143            BinOp::FAdd | BinOp::FSub | BinOp::FMul | BinOp::FDiv | BinOp::FRem
144        )
145    }
146}
147
148keywords!(CastOp {
149    Trunc = "trunc",
150    ZExt = "zext",
151    SExt = "sext",
152    FPTrunc = "fptrunc",
153    FPExt = "fpext",
154    FPToUI = "fptoui",
155    FPToSI = "fptosi",
156    UIToFP = "uitofp",
157    SIToFP = "sitofp",
158    PtrToInt = "ptrtoint",
159    IntToPtr = "inttoptr",
160    BitCast = "bitcast",
161    AddrSpaceCast = "addrspacecast",
162});
163
164keywords!(IntPredicate {
165    Eq = "eq",
166    Ne = "ne",
167    Ugt = "ugt",
168    Uge = "uge",
169    Ult = "ult",
170    Ule = "ule",
171    Sgt = "sgt",
172    Sge = "sge",
173    Slt = "slt",
174    Sle = "sle",
175});
176
177keywords!(FloatPredicate {
178    False = "false",
179    Oeq = "oeq",
180    Ogt = "ogt",
181    Oge = "oge",
182    Olt = "olt",
183    Ole = "ole",
184    One = "one",
185    Ord = "ord",
186    Ueq = "ueq",
187    Ugt = "ugt",
188    Uge = "uge",
189    Ult = "ult",
190    Ule = "ule",
191    Une = "une",
192    Uno = "uno",
193    True = "true",
194});
195
196#[derive(Clone, PartialEq, Debug)]
197pub struct Argument {
198    pub ty: Ty,
199    pub attrs: Vec<String>,
200    pub value: Value,
201    pub span: Span,
202}
203
204#[derive(Clone, PartialEq, Debug)]
205pub struct Call {
206    pub tail: bool,
207    pub ret_ty: Ty,
208    pub explicit_fn_ty: Option<Ty>,
209    pub callee: Value,
210    pub args: Vec<Argument>,
211    pub attr_groups: Vec<String>,
212    pub span: Span,
213}
214
215impl Call {
216    pub fn callee_name(&self) -> Option<&str> {
217        match &self.callee {
218            Value::Global(name) => Some(name),
219            _ => None,
220        }
221    }
222}
223
224#[derive(Clone, PartialEq, Debug)]
225pub enum InstKind {
226    Call(Call),
227    Binary {
228        op: BinOp,
229        ty: Ty,
230        lhs: Value,
231        rhs: Value,
232    },
233    ICmp {
234        pred: IntPredicate,
235        ty: Ty,
236        lhs: Value,
237        rhs: Value,
238    },
239    FCmp {
240        pred: FloatPredicate,
241        ty: Ty,
242        lhs: Value,
243        rhs: Value,
244    },
245    Cast {
246        op: CastOp,
247        operand: TypedValue,
248        to: Ty,
249    },
250    Select {
251        cond: TypedValue,
252        if_true: TypedValue,
253        if_false: TypedValue,
254    },
255    Phi {
256        ty: Ty,
257        incoming: Vec<(Value, String)>,
258    },
259    Alloca {
260        ty: Ty,
261        count: Option<TypedValue>,
262    },
263    Load {
264        ty: Ty,
265        ptr: TypedValue,
266    },
267    Store {
268        value: TypedValue,
269        ptr: TypedValue,
270    },
271    GetElementPtr {
272        inbounds: bool,
273        base_ty: Ty,
274        ptr: TypedValue,
275        indices: Vec<TypedValue>,
276    },
277    ExtractValue {
278        aggregate: TypedValue,
279        indices: Vec<u64>,
280    },
281    InsertValue {
282        aggregate: TypedValue,
283        value: TypedValue,
284        indices: Vec<u64>,
285    },
286    Freeze(TypedValue),
287    Fence,
288    Unsupported {
289        opcode: String,
290    },
291}
292
293#[derive(Clone, PartialEq, Debug)]
294pub struct Instruction {
295    pub result: Option<String>,
296    pub kind: InstKind,
297    pub span: Span,
298}
299
300#[derive(Clone, PartialEq, Debug)]
301pub enum Terminator {
302    Ret(Option<TypedValue>),
303    Br {
304        target: String,
305    },
306    CondBr {
307        cond: TypedValue,
308        if_true: String,
309        if_false: String,
310    },
311    Switch {
312        scrutinee: TypedValue,
313        default: String,
314        cases: Vec<(TypedValue, String)>,
315    },
316    Unreachable,
317}
318
319#[derive(Clone, PartialEq, Debug)]
320pub struct BasicBlock {
321    pub label: String,
322    pub instructions: Vec<Instruction>,
323    pub terminator: Terminator,
324    pub span: Span,
325}
326
327#[derive(Clone, PartialEq, Debug)]
328pub struct Param {
329    pub ty: Ty,
330    pub name: Option<String>,
331    pub attrs: Vec<String>,
332    pub span: Span,
333}
334
335#[derive(Clone, PartialEq, Debug)]
336pub struct FuncSig {
337    pub name: String,
338    pub ret_ty: Ty,
339    pub params: Vec<Param>,
340    pub varargs: bool,
341    pub attr_groups: Vec<String>,
342    pub attrs: Vec<Attribute>,
343    pub span: Span,
344}
345
346#[derive(Clone, PartialEq, Debug)]
347pub struct Function {
348    pub sig: FuncSig,
349    pub blocks: Vec<BasicBlock>,
350    pub span: Span,
351}
352
353impl Function {
354    pub fn block(&self, label: &str) -> Option<&BasicBlock> {
355        self.blocks.iter().find(|b| b.label == label)
356    }
357}
358
359#[derive(Clone, PartialEq, Eq, Debug)]
360pub enum Attribute {
361    Flag(String),
362    KeyValue(String, String),
363}
364
365impl Attribute {
366    pub fn key(&self) -> &str {
367        match self {
368            Attribute::Flag(k) | Attribute::KeyValue(k, _) => k,
369        }
370    }
371
372    pub fn value(&self) -> Option<&str> {
373        match self {
374            Attribute::Flag(_) => None,
375            Attribute::KeyValue(_, v) => Some(v),
376        }
377    }
378}
379
380#[derive(Clone, PartialEq, Eq, Debug)]
381pub struct AttrGroup {
382    pub id: String,
383    pub attrs: Vec<Attribute>,
384    pub span: Span,
385}
386
387#[derive(Clone, PartialEq, Debug)]
388pub struct GlobalVar {
389    pub name: String,
390    pub ty: Ty,
391    pub initializer: Option<Value>,
392    pub is_constant: bool,
393    pub linkage: Vec<String>,
394    pub span: Span,
395}
396
397#[derive(Clone, PartialEq, Debug)]
398pub struct TypeDef {
399    pub name: String,
400    pub ty: Ty,
401    pub span: Span,
402}
403
404#[derive(Clone, PartialEq, Debug)]
405pub struct NamedMetadata {
406    pub name: String,
407    pub operands: Vec<String>,
408    pub span: Span,
409}
410
411#[derive(Clone, PartialEq, Debug)]
412pub enum MetadataNode {
413    Tuple(Vec<MetadataItem>),
414    Specialized { kind: String, body: String },
415}
416
417#[derive(Clone, PartialEq, Debug)]
418pub enum MetadataItem {
419    Value(TypedValue),
420    Ref(String),
421    Str(String),
422    Node(Vec<MetadataItem>),
423    Null,
424}
425
426#[derive(Clone, PartialEq, Debug)]
427pub struct MetadataDef {
428    pub id: String,
429    pub distinct: bool,
430    pub node: MetadataNode,
431    pub span: Span,
432}
433
434#[derive(Clone, PartialEq, Debug, Default)]
435pub struct Module {
436    pub source_filename: Option<String>,
437    pub datalayout: Option<String>,
438    pub triple: Option<String>,
439    pub type_defs: Vec<TypeDef>,
440    pub globals: Vec<GlobalVar>,
441    pub declarations: Vec<FuncSig>,
442    pub functions: Vec<Function>,
443    pub attr_groups: Vec<AttrGroup>,
444    pub named_metadata: Vec<NamedMetadata>,
445    pub metadata: Vec<MetadataDef>,
446}
447
448impl Module {
449    pub fn function(&self, name: &str) -> Option<&Function> {
450        self.functions.iter().find(|f| f.sig.name == name)
451    }
452
453    pub fn attr_group(&self, id: &str) -> Option<&AttrGroup> {
454        self.attr_groups.iter().find(|g| g.id == id)
455    }
456
457    pub fn global(&self, name: &str) -> Option<&GlobalVar> {
458        self.globals.iter().find(|g| g.name == name)
459    }
460
461    pub fn metadata_def(&self, id: &str) -> Option<&MetadataDef> {
462        self.metadata.iter().find(|m| m.id == id)
463    }
464
465    pub fn named_metadata_node(&self, name: &str) -> Option<&NamedMetadata> {
466        self.named_metadata.iter().find(|n| n.name == name)
467    }
468
469    pub fn attributes_of<'a>(&'a self, sig: &'a FuncSig) -> Vec<&'a Attribute> {
470        let mut out: Vec<&Attribute> = sig.attrs.iter().collect();
471        for id in &sig.attr_groups {
472            if let Some(group) = self.attr_group(id) {
473                out.extend(group.attrs.iter());
474            }
475        }
476        out
477    }
478
479    pub fn entry_point(&self) -> Option<&Function> {
480        self.functions
481            .iter()
482            .find(|f| {
483                self.attributes_of(&f.sig)
484                    .iter()
485                    .any(|a| a.key() == "entry_point")
486            })
487            .or_else(|| self.function("main"))
488    }
489}