Page MenuHomePhabricator

[clang][Interp] Implement while and do-while loops
ClosedPublic

Authored by tbaeder on Oct 7 2022, 2:43 AM.

Details

Summary

I was wondering whether it is somehow possible to get a loop into a expression so I can use it directly in a static_assert() (and it would be interpreted directly rather than compiled to bytecode).

Diff Detail

Event Timeline

tbaeder created this revision.Oct 7 2022, 2:43 AM
Herald added a project: Restricted Project. · View Herald TranscriptOct 7 2022, 2:43 AM
tbaeder requested review of this revision.Oct 7 2022, 2:43 AM
Herald added a project: Restricted Project. · View Herald TranscriptOct 7 2022, 2:43 AM
Herald added a subscriber: cfe-commits. · View Herald Transcript
tbaeder updated this revision to Diff 466022.Oct 7 2022, 3:21 AM

Add break and continue support as well.

aaron.ballman added inline comments.Oct 7 2022, 12:17 PM
clang/test/AST/Interp/loops.cpp
94

Can you also add some tests that use nested loops with multiple levels of break and continue use?

Also, I think it might be useful to show the jump statements causing code to be an invalid constant expression, as in:

constexpr int foo() {
  int i;

  do {
    break;
    i = 12;
  } while (1);

  return i;
}

constexpr int f = foo();
tbaeder added inline comments.Oct 7 2022, 11:29 PM
clang/test/AST/Interp/loops.cpp
94

I can add a commented-out test case for that, but it is currently being rejected for the wrong reasons. I investigated that in another case already and it will simply be rejected because the variable declaration does not have an initializer. Not because we're reading an uninitialized variable.

tbaeder updated this revision to Diff 466259.Oct 7 2022, 11:53 PM
shafik added inline comments.Oct 9 2022, 9:30 PM
clang/test/AST/Interp/loops.cpp
10

infinite loop w/o a side effect are undefined behavior and so should be ill-formed and generate a diagnostic e.g. while(1);, so we should check these cases.

tbaeder added inline comments.Oct 10 2022, 1:03 AM
clang/test/AST/Interp/loops.cpp
10

I think that's better done with a more general approach that limits the iteration count for all loops like the current interpreter does. But that would probably blow up this patch too much.

Unfortunately I can't add test case for the case you describe because the clang process with the new interpreter would never terminate :) Can add a commented-out version though.

shafik added inline comments.Oct 10 2022, 9:49 AM
clang/test/AST/Interp/loops.cpp
10

I think that is fine approach for now.

aaron.ballman accepted this revision.Oct 10 2022, 11:35 AM

LGTM!

clang/lib/AST/Interp/ByteCodeStmtGen.cpp
279
This revision is now accepted and ready to land.Oct 10 2022, 11:35 AM
This revision was automatically updated to reflect the committed changes.
tbaeder marked an inline comment as done.