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
//! Infrastructure of lifting the data representation (DR) into structured
//! representation (SR).

mod storage;

use self::storage::LiftStorage;
use crate::{
    dr,
    sr::{instructions, module, ops, storage::Token, Constant, StructMember, Type},
};

use std::{borrow::Borrow, mem};

/// A structure that we associate an <id> with, containing
/// both the operation token and the result type.
struct OpInfo {
    op: Token<ops::Op>,
    ty: Option<Token<Type>>,
}

impl Borrow<Token<ops::Op>> for OpInfo {
    fn borrow(&self) -> &Token<ops::Op> {
        &self.op
    }
}

pub struct LiftContext {
    //current_block: Option<Token<module::Block>>,
    types: LiftStorage<Type>,
    constants: LiftStorage<Constant>,
    blocks: LiftStorage<module::Block>,
    ops: LiftStorage<ops::Op, OpInfo>,
}

include!("autogen_context.rs");

/// Error lifting a data representation of an operand into the structured
/// representation.
#[derive(Clone, Debug)]
pub enum OperandError {
    /// Operand has a wrong type.
    WrongType,
    /// Operand is an integer value that corresponds to a specified enum,
    /// but the given integer is not known to have a mapping.
    WrongEnumValue,
    /// Operand is missing from the list.
    Missing,
}

/// Error lifting a data representation of an instruction.
#[derive(Clone, Debug)]
pub enum InstructionError {
    /// Instruction has a wrong opcode.
    WrongOpcode,
    /// Instruction is missing a result <id> or type.
    MissingResult,
    /// One of the operands can not be lifted.
    Operand(OperandError),
}

impl From<OperandError> for InstructionError {
    fn from(error: OperandError) -> Self {
        InstructionError::Operand(error)
    }
}

/// Error that may occur during the convesion from the data representation
/// of a module into a structured representation.
#[derive(Clone, Debug)]
pub enum ConversionError {
    MissingHeader,
    MissingFunction,
    MissingFunctionType,
    MissingLabel,
    MissingTerminator,
    Instruction(InstructionError),
}

impl From<InstructionError> for ConversionError {
    fn from(error: InstructionError) -> Self {
        ConversionError::Instruction(error)
    }
}

impl LiftContext {
    /// Convert a module from the data representation into structured representation.
    pub fn convert(module: &dr::Module) -> Result<module::Module, ConversionError> {
        let mut context = LiftContext {
            types: LiftStorage::new(),
            constants: LiftStorage::new(),
            blocks: LiftStorage::new(),
            ops: LiftStorage::new(),
        };
        let mut functions = Vec::new();
        let entry_points = Vec::new();

        for inst in module.types_global_values.iter() {
            match context.lift_type(inst) {
                Ok(value) => {
                    if let Some(id) = inst.result_id {
                        context.types.append_id(id, value);
                    }
                    continue;
                }
                Err(InstructionError::WrongOpcode) => {}
                Err(e) => panic!("Type lift error: {:?}", e),
            }
            match context.lift_constant(inst) {
                Ok(value) => {
                    if let Some(id) = inst.result_id {
                        context.constants.append_id(id, value);
                    }
                    continue;
                }
                Err(InstructionError::WrongOpcode) => {}
                Err(e) => panic!("Constant lift error: {:?}", e),
            }
        }

        for fun in module.functions.iter() {
            let def =
                context.lift_function(fun.def.as_ref().ok_or(ConversionError::MissingFunction)?)?;
            //TODO: lift function type instruction

            for block in fun.blocks.iter() {
                let mut arguments = Vec::new();
                for inst in &block.instructions {
                    match inst.class.opcode {
                        spirv::Op::Line => {} // skip line decorations
                        spirv::Op::Phi => {
                            let ty = context.types.lookup_token(
                                inst.result_type.ok_or(InstructionError::MissingResult)?,
                            );
                            arguments.push(ty);

                            // Sanity-check if all source variables are of the same type
                            for op in inst.operands.iter().step_by(2) {
                                match op {
                                    dr::Operand::IdRef(id) => {
                                        if let Some((_, info)) = context.ops.lookup_safe(*id) {
                                            assert_eq!(Some(ty), info.ty);
                                        } else {
                                            // let (v, info) =
                                            //     context.constants.lookup_safe(*id).unwrap();
                                            // TODO: Can't convert Constant back to their lowered type yet!
                                            // assert_eq!(Some(ty), info.ty.as_ref());
                                        }
                                    }
                                    _ => {
                                        return Err(ConversionError::Instruction(
                                            InstructionError::Operand(OperandError::Missing),
                                        ))
                                    }
                                };
                            }
                        }
                        _ => {
                            if let Some(id) = inst.result_id {
                                let op = context.lift_op(inst)?;
                                let types = &context.types;
                                let (token, entry) = context.ops.append(id, op);
                                entry.insert(OpInfo {
                                    op: token,
                                    ty: inst.result_type.map(|ty| *types.lookup(ty).1),
                                });
                            }
                        }
                    }
                }

                let terminator = context.lift_terminator(
                    block
                        .instructions
                        .last()
                        .ok_or(ConversionError::MissingTerminator)?,
                )?;

                context.blocks.append_id(
                    block.label.as_ref().unwrap().result_id.unwrap(),
                    module::Block {
                        arguments,
                        ops: Vec::new(),
                        terminator,
                    },
                );
            }

            let start_label = fun.blocks[0].label.as_ref().unwrap().result_id.unwrap();
            let start_block = context.blocks.lookup_token(start_label);
            let blocks = mem::replace(&mut context.blocks, LiftStorage::new()).unwrap();

            functions.push(module::Function {
                control: def.function_control,
                result: context.types.append_id(1, Type::Void), //TODO: fty.return_type,
                parameters: Vec::new(),
                blocks,
                start_block,
            });
        }

        Ok(module::Module {
            version: match module.header {
                Some(ref header) => header.version,
                None => return Err(ConversionError::MissingHeader),
            },
            capabilities: module
                .capabilities
                .iter()
                .map(|cap| context.lift_capability(cap).map(|cap| cap.capability))
                .collect::<Result<_, InstructionError>>()?,
            extensions: Vec::new(),
            ext_inst_imports: Vec::new(),
            memory_model: match module.memory_model {
                Some(ref mm) => context.lift_memory_model(mm)?,
                None => return Err(ConversionError::MissingHeader),
            },
            entry_points,
            types: context.types.unwrap(),
            constants: context.constants.unwrap(),
            ops: context.ops.unwrap(),
            functions,
        })
    }

    fn lookup_jump(&self, destination: spirv::Word) -> module::Jump {
        let (_, block) = self.blocks.lookup(destination);
        module::Jump {
            block: *block,
            arguments: Vec::new(), //TODO
        }
    }

    fn lift_constant(&self, inst: &dr::Instruction) -> Result<Constant, InstructionError> {
        match inst.class.opcode {
            spirv::Op::ConstantTrue => Ok(Constant::Bool(true)),
            spirv::Op::ConstantFalse => Ok(Constant::Bool(false)),
            spirv::Op::Constant => {
                match inst.result_type {
                    Some(id) => {
                        let oper = inst
                            .operands
                            .first()
                            .ok_or(InstructionError::Operand(OperandError::Missing))?;
                        let (value, width) = match *self.types.lookup(id).0 {
                            Type::Int {
                                signedness: 0,
                                width,
                            } => match *oper {
                                dr::Operand::LiteralInt32(v) => (Constant::UInt(v), width),
                                _ => {
                                    return Err(InstructionError::Operand(OperandError::WrongType))
                                }
                            },
                            Type::Int { width, .. } => match *oper {
                                dr::Operand::LiteralInt32(v) => (Constant::Int(v as i32), width),
                                _ => {
                                    return Err(InstructionError::Operand(OperandError::WrongType))
                                }
                            },
                            Type::Float { width } => match *oper {
                                dr::Operand::LiteralFloat32(v) => (Constant::Float(v), width),
                                _ => {
                                    return Err(InstructionError::Operand(OperandError::WrongType))
                                }
                            },
                            _ => return Err(InstructionError::MissingResult),
                        };
                        if width > 32 {
                            //log::warn!("Constant <id> {} doesn't fit in 32 bits", id);
                        }
                        Ok(value)
                    }
                    _ => Err(InstructionError::MissingResult),
                }
            }
            spirv::Op::ConstantComposite => {
                let mut vec = Vec::with_capacity(inst.operands.len());
                for oper in inst.operands.iter() {
                    let token = match *oper {
                        dr::Operand::IdRef(v) => self.constants.lookup_token(v),
                        _ => return Err(InstructionError::Operand(OperandError::WrongType)),
                    };
                    vec.push(token);
                }
                Ok(Constant::Composite(vec))
            }
            spirv::Op::ConstantSampler => {
                if inst.operands.len() < 3 {
                    return Err(InstructionError::Operand(OperandError::Missing));
                }
                Ok(Constant::Sampler {
                    addressing_mode: match inst.operands[0] {
                        dr::Operand::SamplerAddressingMode(v) => v,
                        _ => return Err(InstructionError::Operand(OperandError::WrongType)),
                    },
                    normalized: match inst.operands[1] {
                        dr::Operand::LiteralInt32(v) => v != 0,
                        _ => return Err(InstructionError::Operand(OperandError::WrongType)),
                    },
                    filter_mode: match inst.operands[2] {
                        dr::Operand::SamplerFilterMode(v) => v,
                        _ => return Err(InstructionError::Operand(OperandError::WrongType)),
                    },
                })
            }
            spirv::Op::ConstantNull => Ok(Constant::Null),
            _ => Err(InstructionError::WrongOpcode),
        }
    }
}