for loop behaves like do .. while
- Dominant language
- LLVM
- Stars
- 40.5k
- Forks
- 18.7k
- PR merge metrics
- PR metrics pending
Description
## What
Current implementation of [ForExprAST](https://github.com/llvm/llvm-project/blob/main/llvm/examples/Kaleidoscope/Chapter8/toy.cpp#L910) behaves like `do .. while`, the body is executed always at least once, which is incorrect.
## Why
The end condition is [checked](https://github.com/llvm/llvm-project/blob/main/llvm/examples/Kaleidoscope/Chapter8/toy.cpp#L977) in the loop basic block after the body expression.
## How
We need to check the condition before the body is executed. A possible fix is provided in [ir_code_generator.cpp](https://github.com/popescun/llvm-kaleidoscope/blob/main/ir_code_generator.cpp#L480), where body expression is moved to a separate basic block. Now the emitted code looks as:
```cpp
/**
* Output for-oop as:
* entry:
* var = alloca double
* start = startexpr
* store start -> var
* goto loop
*
* loop:
* curvar = load var
* endcond = endxpr
* br endcond, body, afterloop
*
* body:
* bodyexpr
* step = stepexpr
* nextvar = curvar + step
* store nextvar -> var
* br endcond, loop, afterloop
*
* afterlopp:
* return 0.0
*/
```
Contributor guide
Research direction
Read llvm/examples/Kaleidoscope/Chapter8/toy.cpp, starting at ForExprAST and the condition check near the linked lines. Trace the emitted basic blocks and verify that the end condition is evaluated before the body. Done means a false initial condition skips the body while normal iteration still performs the step and repeats correctly.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- cpp
- Domain
- compilers
- Issue type
- Bug
- Difficulty
- 3/5
- Estimated time
- 1-2 days
- Activity status
- Stale
- Clarity
- Clearly specified
- Newbie friendliness
- 52/100