mirror of
https://github.com/tinygo-org/tinygo.git
synced 2026-08-09 13:33:39 +00:00
compiler: properly implement div and rem operations
The division and remainder operations were lowered directly to LLVM IR. This is wrong however because the Go specification defines exactly what happens on a divide by zero or signed integer overflow and LLVM IR itself treats those cases as undefined behavior. Therefore, this commit implements divide by zero and signed integer overflow according to the Go specification. This does have an impact on the generated code, but it is surprisingly small. I've used the drivers repo to test the code before and after, and to my surprise most driver smoke tests are not changed at all. Those that are, have only a small increase in code size. At the same time, this change makes TinyGo more compliant to the Go specification.
This commit is contained in:
committed by
Ron Evans
parent
f99c600ad8
commit
86f1e6aec4
@@ -253,6 +253,19 @@ func (b *builder) createNegativeShiftCheck(shift llvm.Value) {
|
||||
b.createRuntimeAssert(isNegative, "shift", "negativeShiftPanic")
|
||||
}
|
||||
|
||||
// createDivideByZeroCheck asserts that y is not zero. If it is, a runtime panic
|
||||
// will be emitted. This follows the Go specification which says that a divide
|
||||
// by zero must cause a run time panic.
|
||||
func (b *builder) createDivideByZeroCheck(y llvm.Value) {
|
||||
if b.info.nobounds {
|
||||
return
|
||||
}
|
||||
|
||||
// isZero = y == 0
|
||||
isZero := b.CreateICmp(llvm.IntEQ, y, llvm.ConstInt(y.Type(), 0, false), "")
|
||||
b.createRuntimeAssert(isZero, "divbyzero", "divideByZeroPanic")
|
||||
}
|
||||
|
||||
// createRuntimeAssert is a common function to create a new branch on an assert
|
||||
// bool, calling an assert func if the assert value is true (1).
|
||||
func (b *builder) createRuntimeAssert(assert llvm.Value, blockPrefix, assertFunc string) {
|
||||
|
||||
Reference in New Issue
Block a user