Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 7 additions & 1 deletion src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -604,7 +604,13 @@ pub struct ConstDef {

#[derive(Clone, PartialEq, Eq, Hash)]
pub enum ConstKind {
// FIXME(eddyb) maybe merge these? however, their connection is somewhat
// tenuous (being one of the LLVM-isms SPIR-V inherited, among other things),
// there's still the need to rename "global variable" post-`Var`-refactor,
// and last but not least, `PtrToFunc` needs `SPV_INTEL_function_pointers`,
// an OpenCL-only extension Intel came up with for their own SPIR-V tooling.
PtrToGlobalVar(GlobalVar),
PtrToFunc(Func),

// HACK(eddyb) this is a fallback case that should become increasingly rare
// (especially wrt recursive consts), `Rc` means it can't bloat `ConstDef`.
Expand Down Expand Up @@ -696,7 +702,7 @@ pub struct FuncDecl {
pub def: DeclDef<FuncDefBody>,
}

#[derive(Copy, Clone)]
#[derive(Copy, Clone, PartialEq, Eq)]
pub struct FuncParam {
pub attrs: AttrSet,

Expand Down
9 changes: 7 additions & 2 deletions src/print/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1806,7 +1806,7 @@ impl Printer<'_> {
fn sanitize_spv_operand_name<'b>(&self, name: &'b str) -> Option<Cow<'b, str>> {
Some(name).and_then(|name| {
// HACK(eddyb) some operand names are useless.
if name == "Type"
if matches!(name, "Opcode" | "Operand" | "Type")
|| name
.strip_prefix("Operand ")
.is_some_and(|s| s.chars().all(|c| c.is_ascii_digit()))
Expand Down Expand Up @@ -3382,6 +3382,9 @@ impl Print for ConstDef {
&ConstKind::PtrToGlobalVar(gv) => {
pretty::Fragment::new(["&".into(), gv.print(printer)])
}
&ConstKind::PtrToFunc(func) => {
pretty::Fragment::new(["&".into(), func.print(printer)])
}
ConstKind::SpvInst { spv_inst_and_const_inputs } => {
let (spv_inst, const_inputs) = &**spv_inst_and_const_inputs;
pretty::Fragment::new([
Expand Down Expand Up @@ -4146,7 +4149,9 @@ impl Print for FuncAt<'_, DataInst> {
}
}
}
ConstKind::PtrToGlobalVar(_) | ConstKind::SpvTypeOperand(_) => {}
ConstKind::PtrToGlobalVar(_)
| ConstKind::PtrToFunc(_)
| ConstKind::SpvTypeOperand(_) => {}
}
}
None
Expand Down
8 changes: 8 additions & 0 deletions src/qptr/lower.rs
Original file line number Diff line number Diff line change
Expand Up @@ -161,6 +161,14 @@ impl<'a> LowerFromSpvPtrs<'a> {
[spv::Imm::Short(_, sc)] => sc,
_ => unreachable!(),
};

// HACK(eddyb) keep function pointers separate, perhaps eventually
// adding an `OpTypeUntypedPointerKHR CodeSectionINTEL` equivalent
// to SPIR-T itself (after `SPV_KHR_untyped_pointers` support).
if sc == self.wk.CodeSectionINTEL {
return None;
}

let pointee = match type_and_const_inputs[..] {
[TypeOrConst::Type(elem_type)] => elem_type,
_ => unreachable!(),
Expand Down
13 changes: 11 additions & 2 deletions src/spv/lift.rs
Original file line number Diff line number Diff line change
Expand Up @@ -152,7 +152,7 @@ impl Visitor<'_> for NeedsIdsCollector<'_> {
}
let ct_def = &self.cx[ct];
match ct_def.kind {
ConstKind::PtrToGlobalVar(_) | ConstKind::SpvInst { .. } => {
ConstKind::PtrToGlobalVar(_) | ConstKind::PtrToFunc(_) | ConstKind::SpvInst { .. } => {
self.visit_const_def(ct_def);
self.globals.insert(global);
}
Expand Down Expand Up @@ -1073,7 +1073,9 @@ impl LazyInst<'_, '_> {
};
(gv_decl.attrs, import)
}
ConstKind::SpvInst { .. } => (ct_def.attrs, None),
ConstKind::PtrToFunc(_) | ConstKind::SpvInst { .. } => {
(ct_def.attrs, None)
}

// Not inserted into `globals` while visiting.
ConstKind::SpvTypeOperand(_)
Expand Down Expand Up @@ -1192,6 +1194,13 @@ impl LazyInst<'_, '_> {
}
}

&ConstKind::PtrToFunc(func) => spv::InstWithIds {
without_ids: wk.OpConstantFunctionPointerINTEL.into(),
result_type_id: Some(ids.globals[&Global::Type(ct_def.ty)]),
result_id,
ids: [ids.funcs[&func].func_id].into_iter().collect(),
},

ConstKind::SpvInst { spv_inst_and_const_inputs } => {
let (spv_inst, const_inputs) = &**spv_inst_and_const_inputs;
spv::InstWithIds {
Expand Down
192 changes: 143 additions & 49 deletions src/spv/lower.rs
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,11 @@ enum IdDef {

Func(Func),

// HACK(eddyb) despite `FuncBody` deferring ID resolution to allow forward
// references *between* functions, function pointer *constants* need a `Func`
// long before any `OpFunction`s, so they're pre-defined as dummy imports.
FuncForwardRef(Func),

SpvExtInstImport(InternedStr),
SpvDebugString(InternedStr),
}
Expand All @@ -40,7 +45,7 @@ impl IdDef {
IdDef::Type(_) => "a type".into(),
IdDef::Const(_) | IdDef::PtrToGlobalVarForwardRef(_) => "a constant".into(),

IdDef::Func(_) => "a function".into(),
IdDef::Func(_) | IdDef::FuncForwardRef(_) => "a function".into(),

IdDef::SpvExtInstImport(name) => {
format!("`OpExtInstImport {:?}`", &cx[name])
Expand Down Expand Up @@ -172,6 +177,37 @@ impl Module {
assert!(expected == found);
};

// HACK(eddyb) used as the `FuncDecl` for an `IdDef::FuncForwardRef`.
let dummy_decl_for_func_forward_ref = FuncDecl {
attrs: {
let mut attrs = AttrSet::default();
attrs.push_diag(
&cx,
Diag::err(["function ID used as forward reference but never defined".into()]),
);
attrs
},
// FIXME(eddyb) this gets simpler w/ disaggregation.
ret_type: cx.intern(TypeKind::SpvInst {
spv_inst: wk.OpTypeVoid.into(),
type_and_const_inputs: [].into_iter().collect(),
}),
params: [].into_iter().collect(),
def: DeclDef::Imported(Import::LinkName(cx.intern(""))),
};
// HACK(eddyb) no `PartialEq` on `FuncDecl`.
let assert_is_dummy_decl_for_func_forward_ref = |decl: &FuncDecl| {
let [expected, found] = [&dummy_decl_for_func_forward_ref, decl].map(
|FuncDecl { attrs, ret_type, params, def }| {
let DeclDef::Imported(import) = def else {
unreachable!();
};
(attrs, ret_type, params, import)
},
);
assert!(expected == found);
};

let mut module = {
let [magic, version, generator_magic, id_bound, reserved_inst_schema] = parser.header;

Expand Down Expand Up @@ -678,7 +714,8 @@ impl Module {
.map(|&id| match id_defs.get(&id) {
Some(&IdDef::Type(ty)) => Ok(TypeOrConst::Type(ty)),
Some(&IdDef::Const(ct)) => Ok(TypeOrConst::Const(ct)),
None | Some(IdDef::PtrToGlobalVarForwardRef(_)) => {
None
| Some(IdDef::PtrToGlobalVarForwardRef(_) | IdDef::FuncForwardRef(_)) => {
Err(format!("a forward reference to %{id}"))
}
Some(id_def) => Err(id_def.descr(&cx)),
Expand All @@ -696,6 +733,38 @@ impl Module {
});
id_defs.insert(id, IdDef::Type(ty));

Seq::TypeConstOrGlobalVar
} else if opcode == wk.OpConstantFunctionPointerINTEL {
use std::collections::hash_map::Entry;

let id = inst.result_id.unwrap();

let func_id = inst.ids[0];
let func = match id_defs.entry(func_id) {
Entry::Occupied(entry) => match entry.get() {
&IdDef::FuncForwardRef(func) => Ok(func),
id_def => Err(id_def.descr(&cx)),
},
Entry::Vacant(entry) => {
let func =
module.funcs.define(&cx, dummy_decl_for_func_forward_ref.clone());
entry.insert(IdDef::FuncForwardRef(func));
Ok(func)
}
}
.map_err(|descr| {
invalid(&format!(
"unsupported use of {descr} as the `OpConstantFunctionPointerINTEL` operand"
))
})?;

let ct = cx.intern(ConstDef {
attrs: mem::take(&mut attrs),
ty: result_type.unwrap(),
kind: ConstKind::PtrToFunc(func),
});
id_defs.insert(id, IdDef::Const(ct));

Seq::TypeConstOrGlobalVar
} else if inst_category == spec::InstructionCategory::Const || opcode == wk.OpUndef {
let id = inst.result_id.unwrap();
Expand Down Expand Up @@ -790,7 +859,8 @@ impl Module {
let initializer = initializer
.map(|id| match id_defs.get(&id) {
Some(&IdDef::Const(ct)) => Ok(ct),
None | Some(IdDef::PtrToGlobalVarForwardRef(_)) => {
None
| Some(IdDef::PtrToGlobalVarForwardRef(_) | IdDef::FuncForwardRef(_)) => {
Err(format!("a forward reference to %{id}"))
}
Some(id_def) => Err(id_def.descr(&cx)),
Expand Down Expand Up @@ -932,19 +1002,40 @@ impl Module {
})
}
};
let decl = FuncDecl {
attrs: mem::take(&mut attrs),
ret_type: func_ret_type,
params: func_type_param_types
.map(|ty| FuncParam { attrs: AttrSet::default(), ty })
.collect(),
def,
};

let func = module.funcs.define(
&cx,
FuncDecl {
attrs: mem::take(&mut attrs),
ret_type: func_ret_type,
params: func_type_param_types
.map(|ty| FuncParam { attrs: AttrSet::default(), ty })
.collect(),
def,
},
);
id_defs.insert(func_id, IdDef::Func(func));
let func = {
use std::collections::hash_map::Entry;

match id_defs.entry(func_id) {
Entry::Occupied(mut entry) => match entry.get() {
&IdDef::FuncForwardRef(func) => {
let decl_slot = &mut module.funcs[func];
assert_is_dummy_decl_for_func_forward_ref(decl_slot);
*decl_slot = decl;

entry.insert(IdDef::Func(func));
Ok(func)
}
id_def => Err(id_def.descr(&cx)),
},
Entry::Vacant(entry) => {
let func = module.funcs.define(&cx, decl);
entry.insert(IdDef::Func(func));
Ok(func)
}
}
.map_err(|descr| {
invalid(&format!("invalid redefinition of {descr} as a new function"))
})?
};

current_func_body = Some(FuncBody { func_id, func, insts: vec![] });

Expand Down Expand Up @@ -1313,44 +1404,47 @@ impl Module {

// FIXME(eddyb) find a more compact name and/or make this a method.
// FIXME(eddyb) this returns `LocalIdDef` even for global values.
let lookup_global_or_local_id_for_data_or_control_inst_input =
|id| match id_defs.get(&id) {
Some(&IdDef::Type(ty)) => {
Ok(LocalIdDef::Value(Value::Const(spv_type_operand_as_const(ty))))
}
Some(&IdDef::Const(ct)) => Ok(LocalIdDef::Value(Value::Const(ct))),
Some(id_def @ IdDef::Func(_)) => Err(invalid(&format!(
"unsupported use of {} outside `OpFunctionCall`",
id_def.descr(&cx),
))),
Some(id_def @ IdDef::SpvDebugString(s)) => {
if opcode == wk.OpExtInst {
// HACK(eddyb) intern `OpString`s as `Const`s on
// the fly, as it's a less likely usage than the
// `OpLine` one.
let ct = cx.intern(ConstDef {
attrs: AttrSet::default(),
ty: cx.intern(TypeKind::SpvStringLiteralForExtInst),
kind: ConstKind::SpvStringLiteralForExtInst(*s),
});
Ok(LocalIdDef::Value(Value::Const(ct)))
} else {
Err(invalid(&format!(
"unsupported use of {} outside `OpSource`, \
let lookup_global_or_local_id_for_data_or_control_inst_input = |id| match id_defs
.get(&id)
{
Some(&IdDef::Type(ty)) => {
Ok(LocalIdDef::Value(Value::Const(spv_type_operand_as_const(ty))))
}
Some(&IdDef::Const(ct)) => Ok(LocalIdDef::Value(Value::Const(ct))),
Some(id_def @ IdDef::Func(_)) => Err(invalid(&format!(
"unsupported use of {} outside `OpFunctionCall`",
id_def.descr(&cx),
))),
Some(id_def @ IdDef::SpvDebugString(s)) => {
if opcode == wk.OpExtInst {
// HACK(eddyb) intern `OpString`s as `Const`s on
// the fly, as it's a less likely usage than the
// `OpLine` one.
let ct = cx.intern(ConstDef {
attrs: AttrSet::default(),
ty: cx.intern(TypeKind::SpvStringLiteralForExtInst),
kind: ConstKind::SpvStringLiteralForExtInst(*s),
});
Ok(LocalIdDef::Value(Value::Const(ct)))
} else {
Err(invalid(&format!(
"unsupported use of {} outside `OpSource`, \
`OpLine`, or `OpExtInst`",
id_def.descr(&cx),
)))
}
id_def.descr(&cx),
)))
}
Some(id_def @ IdDef::SpvExtInstImport(_)) => Err(invalid(&format!(
"unsupported use of {} outside `OpExtInst`",
id_def.descr(&cx),
))),
None | Some(IdDef::PtrToGlobalVarForwardRef(_)) => local_id_defs
}
Some(id_def @ IdDef::SpvExtInstImport(_)) => Err(invalid(&format!(
"unsupported use of {} outside `OpExtInst`",
id_def.descr(&cx),
))),
None | Some(IdDef::PtrToGlobalVarForwardRef(_) | IdDef::FuncForwardRef(_)) => {
local_id_defs
.get(&id)
.copied()
.ok_or_else(|| invalid(&format!("undefined ID %{id}",))),
};
.ok_or_else(|| invalid(&format!("undefined ID %{id}",)))
}
};

if opcode == wk.OpFunctionParameter {
if current_block.is_some() {
Expand Down
Loading
Loading