M
Modular14mo ago
sa-code

Branchless way to convert bool to int?

Right now I do something like
# assuming b is a bool
let x = 1 if b else 0
# assuming b is a bool
let x = 1 if b else 0
Is there a way to do this in a branchless way? b.to_int() doesn't exist
7 Replies
Stole
Stole14mo ago
You can do it with mlir like such:
Int(__mlir_op.`index.castu`[_type : __mlir_type.index](b.__mlir_i1__()))
Int(__mlir_op.`index.castu`[_type : __mlir_type.index](b.__mlir_i1__()))
But I think the more readable solution is to just construct a SIMD UInt8: UInt8(b).to_int()
sa-code
sa-codeOP14mo ago
thanks ❤️ I don't speak MLIR so it's nice to have that. How did you learn it?
Stole
Stole14mo ago
A lot of trial and error so far haha I don't know how else to. I've been relying on Mojo errors (and lots of crashes!) for more info on internal types and whatnot.
sa-code
sa-codeOP14mo ago
You have my respect
aetherclouds
aetherclouds14mo ago
@Stole sorry if I'm bugging but how or where do you learn the mlir methods? like I'm wondering now if all types can cast to each other through something.__mlir_somethingelse__()? I can't even tell what goes in backticks and what doesn't anymore 😔
Stole
Stole14mo ago
Yeah it is pretty confusing. The only __mlir_somethingelse__()'s I've seen are just __mlir_index__() and __mlir_i1__() (respectively, from the Int and Bool structs). I think that more very well might get added in the future, but I guess they only decided to add these since it's what the types in the standard library commanded. These also will likely only be for basic MLIR types from the builtin dialect, such as the integer types: https://mlir.llvm.org/docs/Dialects/Builtin/#integertype.
aetherclouds
aetherclouds14mo ago
sorry I read this and forgot to reply but okay and thank you! (ngl it I hope somebody does a write up on a big picture overview of the dialect and its interactions with SIMD because it's all very new to me hence confusing. like scouring the web for resources on it)
Want results from more Discord servers?
Add your server