[PATCH] D122686: Fold calls to strnlen (PR46455)
Martin Sebor via Phabricator via llvm-commits
llvm-commits at lists.llvm.org
Tue Mar 29 14:30:17 PDT 2022
msebor created this revision.
msebor added reviewers: beanz, DavidKreitzer, MatzeB, xbolva00.
Herald added subscribers: pengfei, hiraditya.
Herald added a project: All.
msebor requested review of this revision.
Herald added a project: LLVM.
Herald added a subscriber: llvm-commits.
This patch adds support for folding simple `strnlen` calls to `SimplifyLibCalls.cpp`. It extends the `optimizeStringLength` member function to accept the `bound` AKA `maxlen` argument to `strnlen` and attempt to fold calls to it analogously to `strlen`. To keep `optimizeStringLength` from growing unwieldy the patch factors out the string length logic into a new helper function, `minStringLength`, and adds most of the `strnlen` folding there.
The new `minStringLength` function can be called recursively to simplify some less than completely trivial calls with conditional expressions such as `strnlen(x ? "123" : "12345" + i, n)`. In case one of the recursive calls fails, rather than creating and inserting the simplified instructions into the IR as it goes, the function returns a pointer to a function/lambda that does that. On success the caller then evaluates the lambda to create and insert the instructions (or constants) into the IR.
I have tested the patch by bootstrapping LLVM + Clang on x86_64-linux and running `check-all`.
If there are better solutions than the lambda approach above I'd be happy to learn about them and adjust the patch (and follow up on the question I posted about this on Discourse: https://discourse.llvm.org/t/61309).
The new `minStringLength` function can also be called to implement `wcsnlen` folding. I have done that in a separate patch that I'll submit if/when this is accepted.
Repository:
rG LLVM Github Monorepo
https://reviews.llvm.org/D122686
Files:
llvm/include/llvm/Transforms/Utils/SimplifyLibCalls.h
llvm/lib/Transforms/Utils/SimplifyLibCalls.cpp
llvm/test/Transforms/InstCombine/strlen-4.ll
llvm/test/Transforms/InstCombine/strnlen-1.ll
llvm/test/Transforms/InstCombine/strnlen-2.ll
llvm/test/Transforms/InstCombine/strnlen-3.ll
llvm/test/Transforms/InstCombine/strnlen-4.ll
llvm/test/Transforms/InstCombine/strnlen-5.ll
llvm/test/Transforms/InstCombine/strnlen-6.ll
llvm/test/Transforms/InstCombine/wcslen-5.ll
-------------- next part --------------
A non-text attachment was scrubbed...
Name: D122686.418980.patch
Type: text/x-patch
Size: 46372 bytes
Desc: not available
URL: <http://lists.llvm.org/pipermail/llvm-commits/attachments/20220329/f48053e9/attachment.bin>
More information about the llvm-commits
mailing list