llhd 0.16.0

A Low Level Hardware Description that acts as a foundation for building hardware design tools.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
// Copyright (c) 2017-2021 Fabian Schuiki

//! Emitting LLHD IR assembly.

use crate::ir::{prelude::*, UnitKind};
use std::{
    collections::{HashMap, HashSet},
    io::{Result, Write},
    rc::Rc,
};

/// Temporary object to emit LLHD IR assembly.
pub struct Writer<T> {
    sink: T,
}

impl<T: Write> Writer<T> {
    /// Create a new assembly writer.
    pub fn new(sink: T) -> Self {
        Self { sink }
    }

    /// Emit assembly for a module.
    pub fn write_module(&mut self, module: &Module) -> Result<()> {
        let mut separate = false;
        for unit in module.units() {
            if separate {
                write!(self.sink, "\n")?;
            }
            separate = true;
            self.write_unit(unit)?;
        }
        for decl in module.decls() {
            if separate {
                write!(self.sink, "\n")?;
            }
            separate = false;
            let data = &module[decl];
            self.write_declaration(&data.sig, &data.name)?;
        }
        Ok(())
    }

    /// Emit assembly for a unit.
    pub fn write_unit(&mut self, data: Unit) -> Result<()> {
        let mut uw = UnitWriter::new(self, data);
        write!(uw.writer.sink, "{} {} (", data.kind(), data.name())?;
        let mut comma = false;
        for arg in data.sig().inputs() {
            if comma {
                write!(uw.writer.sink, ", ")?;
            }
            comma = true;
            write!(uw.writer.sink, "{} ", data.sig().arg_type(arg))?;
            uw.write_value_name(data.arg_value(arg))?;
        }
        if data.kind() == UnitKind::Function {
            write!(uw.writer.sink, ") {} {{\n", data.sig().return_type())?;
        } else {
            write!(uw.writer.sink, ") -> (")?;
            let mut comma = false;
            for arg in data.sig().outputs() {
                if comma {
                    write!(uw.writer.sink, ", ")?;
                }
                comma = true;
                write!(uw.writer.sink, "{} ", data.sig().arg_type(arg))?;
                uw.write_value_name(data.arg_value(arg))?;
            }
            write!(uw.writer.sink, ") {{\n")?;
        }
        for block in data.blocks() {
            if data.kind() != UnitKind::Entity {
                uw.write_block_name(block)?;
                write!(uw.writer.sink, ":\n")?;
            }
            for inst in data.insts(block) {
                if data[inst].opcode().is_terminator() && data.is_entity() {
                    continue;
                }
                write!(uw.writer.sink, "    ")?;
                uw.write_inst(inst)?;
                write!(uw.writer.sink, "\n")?;
            }
        }
        write!(uw.writer.sink, "}}\n")?;
        Ok(())
    }

    /// Emit assembly for a declaration.
    pub fn write_declaration(&mut self, sig: &Signature, name: &UnitName) -> Result<()> {
        write!(self.sink, "declare {} {}\n", name, sig)?;
        Ok(())
    }
}

pub struct UnitWriter<'a, T> {
    writer: &'a mut Writer<T>,
    unit: Unit<'a>,
    value_names: HashMap<Value, Rc<String>>,
    block_names: HashMap<Block, Rc<String>>,
    name_indices: HashMap<Rc<String>, usize>,
    names: HashSet<Rc<String>>,
    tmp_index: usize,
}

impl<'a, T: Write> UnitWriter<'a, T> {
    /// Create a new writer for a unit.
    pub fn new(writer: &'a mut Writer<T>, unit: Unit<'a>) -> Self {
        Self {
            writer,
            unit,
            value_names: Default::default(),
            block_names: Default::default(),
            name_indices: Default::default(),
            names: Default::default(),
            tmp_index: 0,
        }
    }

    /// Emit the name of a value.
    pub fn write_value_name(&mut self, value: Value) -> Result<()> {
        // If we have already picked a name for the value, use that.
        if let Some(name) = self.value_names.get(&value) {
            return write!(self.writer.sink, "%{}", name);
        }

        // Check if the value has an explicit name set, or if we should just
        // generate a temporary name.
        let name = self.uniquify_name(self.unit.get_name(value));

        // Emit the name and associate it with the value for later reuse.
        write!(self.writer.sink, "%{}", name)?;
        self.value_names.insert(value, name);
        Ok(())
    }

    /// Emit the name of a BB.
    pub fn write_block_name(&mut self, block: Block) -> Result<()> {
        // If we have already picked a name for the value, use that.
        if let Some(name) = self.block_names.get(&block) {
            return write!(self.writer.sink, "{}", name);
        }

        // Check if the block has an explicit name set, or if we should just
        // generate a temporary name.
        let name = self.uniquify_name(self.unit.get_block_name(block));

        // Emit the name and associate it with the block for later reuse.
        write!(self.writer.sink, "{}", name)?;
        self.block_names.insert(block, name);
        Ok(())
    }

    /// Emit the name of a BB to be used as label in an instruction.
    pub fn write_block_value(&mut self, block: Block) -> Result<()> {
        write!(self.writer.sink, "%")?;
        self.write_block_name(block)
    }

    /// Uniquify a value or block name.
    fn uniquify_name(&mut self, name: Option<&str>) -> Rc<String> {
        if let Some(requested_name) = name {
            let requested_name = escape_name(requested_name);
            let idx = self.name_indices.entry(requested_name.clone()).or_insert(0);
            loop {
                let name = if *idx == 0 {
                    requested_name.clone()
                } else {
                    Rc::new(format!("{}{}", requested_name, idx))
                };
                *idx += 1;
                if self.names.insert(name.clone()) {
                    break name;
                }
            }
        } else {
            loop {
                let name = Rc::new(format!("{}", self.tmp_index));
                self.tmp_index += 1;
                if self.names.insert(name.clone()) {
                    break name;
                }
            }
        }
    }

    /// Emit the use of a value.
    pub fn write_value_use(&mut self, value: Value, with_type: bool) -> Result<()> {
        if with_type {
            write!(self.writer.sink, "{} ", self.unit.value_type(value))?;
        }
        self.write_value_name(value)
    }

    /// Emit an instruction.
    pub fn write_inst(&mut self, inst: Inst) -> Result<()> {
        let unit = self.unit;
        if unit.has_result(inst) {
            self.write_value_name(unit.inst_result(inst))?;
            write!(self.writer.sink, " = ")?;
        }
        let data = &unit[inst];
        match data.opcode() {
            Opcode::ConstInt => write!(
                self.writer.sink,
                "{} {} {}",
                data.opcode(),
                unit.value_type(unit.inst_result(inst)),
                data.get_const_int().unwrap().value
            )?,
            Opcode::ConstTime => write!(
                self.writer.sink,
                "{} time {}",
                data.opcode(),
                data.get_const_time().unwrap()
            )?,
            Opcode::ArrayUniform => {
                write!(self.writer.sink, "[{} x ", data.imms()[0])?;
                self.write_value_use(data.args()[0], true)?;
                write!(self.writer.sink, "]")?;
            }
            Opcode::Array => {
                write!(self.writer.sink, "[")?;
                let mut first = true;
                for &arg in data.args() {
                    if !first {
                        write!(self.writer.sink, ", ")?;
                    }
                    self.write_value_use(arg, first)?;
                    first = false;
                }
                write!(self.writer.sink, "]")?;
            }
            Opcode::Struct => {
                write!(self.writer.sink, "{{")?;
                let mut first = true;
                for &arg in data.args() {
                    if !first {
                        write!(self.writer.sink, ", ")?;
                    }
                    first = false;
                    self.write_value_use(arg, true)?;
                }
                write!(self.writer.sink, "}}")?;
            }
            Opcode::Alias
            | Opcode::Not
            | Opcode::Neg
            | Opcode::Add
            | Opcode::Sub
            | Opcode::And
            | Opcode::Or
            | Opcode::Xor
            | Opcode::Smul
            | Opcode::Sdiv
            | Opcode::Smod
            | Opcode::Srem
            | Opcode::Umul
            | Opcode::Udiv
            | Opcode::Umod
            | Opcode::Urem
            | Opcode::Eq
            | Opcode::Neq
            | Opcode::Slt
            | Opcode::Sgt
            | Opcode::Sle
            | Opcode::Sge
            | Opcode::Ult
            | Opcode::Ugt
            | Opcode::Ule
            | Opcode::Uge
            | Opcode::Con
            | Opcode::Del
            | Opcode::Sig
            | Opcode::Prb
            | Opcode::Drv
            | Opcode::Var
            | Opcode::Ld
            | Opcode::St
            | Opcode::RetValue => {
                write!(self.writer.sink, "{} ", data.opcode())?;
                let mut first = true;
                for &arg in data.args() {
                    if !first {
                        write!(self.writer.sink, ", ")?;
                    }
                    self.write_value_use(arg, first)?;
                    first = false;
                }
            }
            Opcode::DrvCond => {
                write!(self.writer.sink, "{} ", data.opcode())?;
                let args = data.args();
                self.write_value_use(args[0], true)?;
                write!(self.writer.sink, " if ")?;
                self.write_value_use(args[3], false)?;
                write!(self.writer.sink, ", ")?;
                self.write_value_use(args[1], false)?;
                write!(self.writer.sink, ", ")?;
                self.write_value_use(args[2], false)?;
            }
            Opcode::Shl | Opcode::Shr | Opcode::Mux => {
                write!(self.writer.sink, "{} ", data.opcode())?;
                let mut comma = false;
                for &arg in data.args() {
                    if comma {
                        write!(self.writer.sink, ", ")?;
                    }
                    comma = true;
                    self.write_value_use(arg, true)?;
                }
            }
            Opcode::Reg => {
                write!(self.writer.sink, "{} ", data.opcode())?;
                self.write_value_use(data.args()[0], true)?;
                for t in data.triggers() {
                    write!(self.writer.sink, ", [")?;
                    self.write_value_use(t.data, false)?;
                    write!(self.writer.sink, ", {} ", t.mode)?;
                    self.write_value_use(t.trigger, false)?;
                    if let Some(gate) = t.gate {
                        write!(self.writer.sink, ", if ")?;
                        self.write_value_use(gate, false)?;
                    }
                    write!(self.writer.sink, "]")?;
                }
            }
            Opcode::InsField | Opcode::InsSlice => {
                write!(self.writer.sink, "{} ", data.opcode())?;
                let mut first = true;
                for &arg in data.args() {
                    if !first {
                        write!(self.writer.sink, ", ")?;
                    }
                    self.write_value_use(arg, true)?;
                    first = false;
                }
                for &imm in data.imms() {
                    write!(self.writer.sink, ", {}", imm)?;
                }
            }
            Opcode::ExtField | Opcode::ExtSlice => {
                write!(
                    self.writer.sink,
                    "{} {}",
                    data.opcode(),
                    unit.inst_type(inst)
                )?;
                for &arg in data.args() {
                    write!(self.writer.sink, ", ")?;
                    self.write_value_use(arg, true)?;
                }
                for &imm in data.imms() {
                    write!(self.writer.sink, ", {}", imm)?;
                }
            }
            Opcode::Call => {
                write!(
                    self.writer.sink,
                    "{} {} {} (",
                    data.opcode(),
                    if unit.has_result(inst) {
                        unit.value_type(unit.inst_result(inst))
                    } else {
                        crate::void_ty()
                    },
                    unit[data.get_ext_unit().unwrap()].name,
                )?;
                let mut comma = false;
                for &arg in data.input_args() {
                    if comma {
                        write!(self.writer.sink, ", ")?;
                    }
                    comma = true;
                    self.write_value_use(arg, true)?;
                }
                write!(self.writer.sink, ")")?;
            }
            Opcode::Inst => {
                write!(
                    self.writer.sink,
                    "{} {} (",
                    data.opcode(),
                    unit[data.get_ext_unit().unwrap()].name,
                )?;
                let mut comma = false;
                for &arg in data.input_args() {
                    if comma {
                        write!(self.writer.sink, ", ")?;
                    }
                    comma = true;
                    self.write_value_use(arg, true)?;
                }
                write!(self.writer.sink, ") -> (")?;
                let mut comma = false;
                for &arg in data.output_args() {
                    if comma {
                        write!(self.writer.sink, ", ")?;
                    }
                    comma = true;
                    self.write_value_use(arg, true)?;
                }
                write!(self.writer.sink, ")")?;
            }
            Opcode::Halt | Opcode::Ret => write!(self.writer.sink, "{}", data.opcode())?,
            Opcode::Phi => {
                write!(
                    self.writer.sink,
                    "{} {} ",
                    data.opcode(),
                    unit.value_type(unit.inst_result(inst))
                )?;
                let mut comma = false;
                for (&arg, &block) in data.args().iter().zip(data.blocks().iter()) {
                    if comma {
                        write!(self.writer.sink, ", ")?;
                    }
                    comma = true;
                    write!(self.writer.sink, "[")?;
                    self.write_value_use(arg, false)?;
                    write!(self.writer.sink, ", ")?;
                    self.write_block_value(block)?;
                    write!(self.writer.sink, "]")?;
                }
            }
            Opcode::Br => {
                write!(self.writer.sink, "{} ", data.opcode())?;
                self.write_block_value(data.blocks()[0])?;
            }
            Opcode::BrCond => {
                write!(self.writer.sink, "{} ", data.opcode())?;
                self.write_value_use(data.args()[0], false)?;
                write!(self.writer.sink, ", ")?;
                self.write_block_value(data.blocks()[0])?;
                write!(self.writer.sink, ", ")?;
                self.write_block_value(data.blocks()[1])?;
            }
            Opcode::Wait => {
                write!(self.writer.sink, "{} ", data.opcode())?;
                self.write_block_value(data.blocks()[0])?;
                for &arg in data.args() {
                    write!(self.writer.sink, ", ")?;
                    self.write_value_use(arg, false)?;
                }
            }
            Opcode::WaitTime => {
                write!(self.writer.sink, "{} ", data.opcode())?;
                self.write_block_value(data.blocks()[0])?;
                write!(self.writer.sink, " for ")?;
                self.write_value_use(data.args()[0], false)?;
                for &arg in &data.args()[1..] {
                    write!(self.writer.sink, ", ")?;
                    self.write_value_use(arg, false)?;
                }
            }
        }
        Ok(())
    }
}

/// Check if a character can be emitted in a name without escaping.
fn is_acceptable_name_char(c: char) -> bool {
    c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z' || c >= '0' && c <= '9' || c == '_' || c == '.'
}

/// Escape the special characters in a name.
fn escape_name(input: &str) -> Rc<String> {
    let mut s = String::with_capacity(input.len());
    for c in input.chars() {
        if is_acceptable_name_char(c) {
            s.push(c);
        } else {
            s.push_str(&format!("\\{:x}", c as u32));
        }
    }
    Rc::new(s)
}