Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Support short-circuiting logical expressions #3572

Closed
strongoier opened this issue Nov 21, 2021 · 2 comments · Fixed by #3632
Closed

Support short-circuiting logical expressions #3572

strongoier opened this issue Nov 21, 2021 · 2 comments · Fixed by #3632
Assignees
Labels
feature request Suggest an idea on this project

Comments

@strongoier
Copy link
Contributor

The following code snippet,

import taichi as ti

ti.init(debug=True)

a = ti.field(ti.i32, shape=10)

@ti.kernel
def func(i: ti.i32):
    if i >= 0 and a[i] != 0:
        print(a[i])

func(-1)

will give a runtime error due to negative indices. This is because in Taichi, logical expressions are completely evaluated anyway. However, most programming languages are using short-circuiting logical expressions, so this behavior difference may cause confusion to newcomers.

I suggest that Taichi can support short-circuiting logical expressions. To avoid affecting performance of existing code, we can have an option in compiler configurations to decide whether to enable the new behavior.

@strongoier strongoier added the feature request Suggest an idea on this project label Nov 21, 2021
@re-xyr
Copy link
Contributor

re-xyr commented Nov 22, 2021

To implement this in the frontend, I think we can translate a and b into the semantics of if a then b else False and a or b into the semantics of if a then True else b. We can use the logic in IRBuilder.build_IfExp(); not sure what the performance impact is going to be.

@strongoier
Copy link
Contributor Author

strongoier commented Nov 22, 2021

The solution makes sense to me!

Regarding the performance impact, branches are considered harmful in GPU programming :-( Therefore, as the first step, I suggest adding an option like ti.init(short_circuit=True) to enable the new behavior. In the future, we may apply more optimizations (e.g. automatically switching back to the non-short-circuiting case if it is definitely safe and faster) to make it the default behavior.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
feature request Suggest an idea on this project
Projects
None yet
Development

Successfully merging a pull request may close this issue.

2 participants