<div dir="ltr"><div>Hi Nandor,</div><div><br></div><div>This sounds like a really cool project, and something that we would significantly benefit from.</div><div><br></div><div>This is an area I've put some thought into in the past. A lot of your decisions below seem good to me; I think there are a few other things you should consider:</div><div><br></div><div> * The current APValue representation is extremely bloated. Each instance is 72 bytes, and every subobject of an object is stored as a distinct APValue, so for instance a single char[128] variable will often occupy 9288 bytes of storage and incurs 128 distinct memory allocations.</div><div> * The current representation of an lvalue as an explicit subobject path is likewise very expensive in terms of memory and distinct allocations.</div><div><br></div><div>I have some pretty concrete ideas for how to solve these problems that I could write up if you're interested in tackling them.</div><div><br></div><div>(Your project name makes me cringe a little; maybe referring to it as ExprVM to match the subdirectory name would be better?)</div><br><div class="gmail_quote"><div dir="ltr" class="gmail_attr">On Wed, 3 Jul 2019 at 10:49, Nandor Licker via cfe-dev <<a href="mailto:cfe-dev@lists.llvm.org" target="_blank">cfe-dev@lists.llvm.org</a>> wrote:<br></div><blockquote class="gmail_quote" style="margin:0px 0px 0px 0.8ex;border-left:1px solid rgb(204,204,204);padding-left:1ex">TL;DR: Fast interpreter for C++ constexpr to replace the existing tree evaluator<br>
<br>
I am a PhD student at the University of Cambridge currently interning at Apple, <br>
working with JF Bastien and Michael Spencer on improving constexpr performance. <br>
Constexpr evaluation is presently slow and difficult since it relies on a <br>
monolithic AST walker. We propose replacing the tree evaluator with a bytecode <br>
interpreter to improve compilation times. The tree evaluator also poses <br>
significant maintenance and scalability problems, which we intend to ameliorate <br>
using the interpreter. While being generally faster, the interpreter does <br>
present two critical issues: a slightly increased memory footprint and added <br>
complexity to the compiler. This tradeoff is justified, as efficient constexpr <br>
evaluation could prove to be valuable as the language evolves.<br>
<br>
We would like to integrate this interpreter into clang. This RFC details the <br>
benefits of an interpreter and describes an initial implementation, along with <br>
a roadmap for replacing almost all of the tree evaluator with the interpreter. <br>
Even without optimizations, the performance of the interpreter matches that of <br>
the tree evaluator, thus the short-term focus is on feature completeness, not <br>
evaluation speed, as reflected by known inefficiencies in the current <br>
implementation. We would highly appreciate comments related to integration into <br>
clang and our roadmap towards replacing the evaluator, as well as feedback on <br>
the initial patch. This project serves mostly as a prototype in order to <br>
determine what kind of bytecode and compiler is required to efficiently evaluate <br>
code and emit useful diagnostic messages, paving the way for a future fast, <br>
potentially JIT-ed, interpreter.<br>
<br>
What?<br>
<br>
The ConstExprPreter is an interpreter for C++ constexpr embedded into the clang <br>
frontend: instead of evaluating constant expressions by walking the AST, the <br>
constexpr interpreter compiles C++ to safe bytecode and executes the bytecode <br>
in accordance with the constexpr semantics, emitting all appropriate <br>
diagnostics. It aims to replace the existing AST walker, which is less efficient <br>
and does not scale well in complexity as the constexpr subset of the C++ <br>
language is expected to increase in the future.<br>
<br>
Why?<br>
<br>
The present constexpr evaluator is a 12.000 LOC monolith defined in <br>
clang/lib/AST/ExprConstant.cpp and poses a performance and maintenance problem. <br>
The tree interpreter limits the complexity of constexpr evaluated in a module by <br>
bounding recursion depth (-fconstexpr-depth=) and bounding the number of <br>
execution steps (-fconstexpr-steps).</blockquote><div><br></div><div>Minor point: while the depth limit does exist primarily to work around problems caused by the recursive implementation, the steps limit is provided to catch infinite loops. (I assume your point is that we could raise this limit commensurately with any performance improvements in the evaluator; that seems reasonable.)</div><div><br></div><blockquote class="gmail_quote" style="margin:0px 0px 0px 0.8ex;border-left:1px solid rgb(204,204,204);padding-left:1ex">This severely limits the complexity of <br>
expression which can be evaluated in a given time budget. Furthermore, because <br>
of complexity, the implementation of certain potential future features on top <br>
of the evaluator, such as exception handling, pose serious difficulties. An <br>
efficient constexpr interpreter is expected to be faster and easily extensible, <br>
ameliorating some of the limitations of the tree evaluator, especially regarding <br>
performance. By improving the evaluation speed of constexpr, we expect to enable <br>
C++ users to replace instances of automatically generated code with complex <br>
constexpr, simplifying and improving the reliability of builds.<br>
<br>
Proposed Roadmap<br>
<br>
* Commit the initial patch which embeds a simple bytecode compiler and <br>
interpreter into clang, alongside the existing constexpr evaluator. This <br>
interpreter only supports a subset of constexpr and is disabled by default.<br></blockquote><div><br></div><div>I notice that this is effectively building another system to convert the AST into a control flow graph. Have you considered using the existing CFG layer for (the majority of) this?</div><div> <br></div><blockquote class="gmail_quote" style="margin:0px 0px 0px 0.8ex;border-left:1px solid rgb(204,204,204);padding-left:1ex">
* Add features to the interpreter, reaching a point where it supports all the <br>
features of the existing evaluator.<br>
<br>
* Turn the interpreter on by default. <br>
<br>
* Move the entry point of the interpreter from function calls to arbitrary <br>
toplevel expressions. In order to avoid performance regressions, a small <br>
subset of features will be evaluated without entering the bytecode compiler <br>
and the VM: for example, frequent integer constant definitions, such as <br>
constexpr int kMask = 1 << sizeof(T). This strategy requires keeping parts of <br>
the existing Int evaluator, but allows the removal of the LValue, Complex, <br>
etc. evaluators, significantly reducing the complexity of ExprConstant.cpp.<br>
<br>
* Remove most of the toplevel evaluator, minus the parts required to interpret <br>
simple expressions. Roles will be reversed: if the evaluator encounters an <br>
unsupported feature, it falls back to the interpreter.<br></blockquote><div><br></div><div>I like this approach a lot.</div><div> </div><blockquote class="gmail_quote" style="margin:0px 0px 0px 0.8ex;border-left:1px solid rgb(204,204,204);padding-left:1ex">
* Remove the flags enabling/forcing the interpreter.<br>
<br>
Initial Implementation<br>
<br>
The initial contribution is available in D64146. This only contains the <br>
minimal interpreter required to compile a basic example. Further patches have <br>
been developed, implementing pointers, which will be submitted for review <br>
afterwards.<br>
<br>
The implementation of the interpreter resides in lib/AST/ExprVM, in the <br>
clang::vm namespace. The sole entry point is from ExprConstant.cpp, in the <br>
HandleFunctionCall method. When this method is invoked in order to evaluate a <br>
function application, the vm::Context attached to each module is retrieved from <br>
ASTContext and an attempt is made to compile and interpret the function with <br>
the given parameters. If this fails, the tree interpreter is used as a fallback, <br>
unless the command line flags explicitly ask for a diagnostic pointing to <br>
unimplemented features. If the interpreter succeeds, the result is converted to <br>
a format compatible with the tree evaluator.<br>
<br>
The bytecode compiler simply walks the AST of each function generating a <br>
vm::Function, linking them together into a vm::Program. Certain peephole <br>
optimizations are performed in the compiler in order to optimize <br>
local/parameter accesses and remove redundant instructions, avoiding the use of <br>
pointers whenever possible. The compiler heavily relies on type information: <br>
the Classify method in vm::Context is used to approximate a type from the AST <br>
with a base type supported by the interpreter. The types and the necessary <br>
utilities are defined in Type.cpp. Presently, only 32-bit integers are <br>
supported, however 8, 16 and 64 bit integers will be added and a fallback onto <br>
APSInt is planned for 128-bits and beyond.<br>
<br>
Internally, the compiler relies on a type classification–PrimType–to decide what <br>
opcodes to emit for a particular operation. The Context::Classify method relies <br>
on target information to decide what internal types to map C/C++ types to, <br>
returning llvm::Optional<PrimType>. In the future, the classification is <br>
expected to be complete, removing a large number of the nullopt-checks from the <br>
compiler.<br>
<br>
The opcodes supported by the VM are defined in Opcodes.inc, a header used to <br>
generate most of the interpreter, as well as the disassembler. The VM is stack <br>
based, since such bytecode is fast to generate and the high upfront cost of <br>
register allocation is avoided. In order to accurately emit diagnostics, the VM <br>
needs to cooperate with the tree interpreter—this is achieved by isolating <br>
diagnostics into the vm::State class, inherited by both EvalInfo and <br>
InterpState. Stack frames now use vm::Frame as their base class, inherited by <br>
InterpFrame and CallStackFrame. This allows the stack frame to be traced through <br>
both the VM and the tree walker effectively. The present focus is on <br>
correctness — a path is kept open to optimize the interpreter and improve <br>
instruction dispatch and memory layout, however this is not the current <br>
priority. The interpreter could also be specialized into two variants: one that <br>
only detects problems, falling back to a slower version which tracks <br>
significantly more metadata for informative diagnostics.<br>
<br>
The interpreter needs to detect pointer accesses that would result in Undefined <br>
Behavior: dereferences and arithmetic on pointers which point to invalid memory <br>
locations. To achieve this, each allocation site has a unique descriptor, <br>
containing the metadata required to emit a diagnostic message. Each allocation <br>
creates a block tracking the descriptor, along with all live pointers to that <br>
block. Whenever a block goes out of scope, all the pointers are invalidated: <br>
instead of pointing to the block, they now point to the descriptor. If such a <br>
pointer is used, a diagnostic is generated and execution stops. This scheme <br>
adds an overhead to pointer arithmetic, as the intrusive linked list of <br>
pointers to a block needs to be maintained. If pointers correctly track the <br>
lifetime of stack objects, no additional cost is paid at deallocation sites as <br>
there are no pointers to invalidate.</blockquote><div><br></div><div>There are a bunch of other ways that pointers might be invalidated, due to lifetime events rather than storage events. For example, changing the active member of a union would prevent access through old pointers to the old active member, and changing the active union member /back/ would make such accesses valid again. Similarly, an explicit destructor call on an object prevents that object from being used, but certain other operations can bring it back to life and make the old pointers / references usable again. How do you intend to handle such cases?</div><div> </div><blockquote class="gmail_quote" style="margin:0px 0px 0px 0.8ex;border-left:1px solid rgb(204,204,204);padding-left:1ex">In the future, we might investigate <br>
different schemes, such as the one in asan (shadow memory + epoch counters), or <br>
garbage collection to keep invalid blocks alive as long as there are pointers <br>
to them.<br>
<br>
Usage<br>
<br>
The proposed patch adds two new flags to clang:<br>
<br>
-fexperimental-constexpr-interpreter:<br>
<br>
Enables the interpreter, but falls back to the tree evaluator when encountering <br>
language features which are not supported.<br>
<br>
-fexperimental-constexpr-force-interpreter:<br>
<br>
Forces the use of the interpreter, generating an error diagnostic whenever an <br>
unsupported feature is encountered.<br>
<br>
The behaviour of the compiler and the format of emitted diagnostics remains <br>
unchanged, unless a bug in clang’s diagnostics is identified. In such a case, <br>
we emit what we consider to be the correct diagnostic.<br>
<br>
Performance<br>
<br>
Since the present evaluator is not optimised for performance, a fair comparison <br>
is difficult to obtain, but we expect the interpreter to outperform the tree <br>
evaluator on most repetitive structures. Benchmarks on 1.000.000 iterations of <br>
the sum_pow function in test/ExprVM/loop.cpp show a ~10× improvement in the <br>
running time of the evaluator. Further tests are required in order to compare <br>
the performance of the interpreter to the tree evaluator when evaluating <br>
smaller, non-repetitive expressions. Once a reasonable subset of constexpr is <br>
implemented in the VM, performance benchmarks on open-source constexpr code <br>
will help us compare the cost of compilation and interpretation to that of <br>
direct evaluation. Since the interpreter is significantly faster, the currently <br>
tight limits on the number of statements and the number of steps can be relaxed.<br>
<br>
Memory Usage<br>
<br>
The constexpr interpreter requires a significant amount of metadata in order to <br>
detect cases of undefined behavior and correctly report diagnostics. The <br>
existing evaluator imposes a massive overhead, since all integers are <br>
represented as APInt and all pointers keep a significant amount of metadata. <br>
This overhead is lowered in the bytecode interpreter by better exploiting type <br>
information: integer constants are fixed width and require no additional <br>
information, while the size of pointer metadata is significantly reduced - 3x <br>
increase in pointer size and a 16-byte overhead per allocation (the interpreter <br>
tracks actual pointers for fast dereferencing, while the evaluator maintains an <br>
lvalue and a path into that lvalue for structure fields, incurring a massive <br>
overhead). Since the present implementation focuses on maintainability and <br>
feature completeness, this can be further reduced in the future.<br>
<br>
The compiled bytecode, quite dense due to the type-specialized opcodes, is <br>
maintained in memory as long as the AST is live, which currently happens to be <br>
live throughout all compilation phases. This adds to the total memory used by <br>
the compiler. In the future, mitigations might be required. Given that the <br>
ground truth—the AST—is present in memory, compiled functions could be <br>
discarded and recompiled on demand, reducing peak memory usage.<br>
<br>
Complexity<br>
<br>
The interpreter duplicates the functionality of the existing evaluator, <br>
presently adding significant complexity to the frontend. Unlike the monolithic <br>
ExprConstant.cpp implementation, the constexpr interpreter is significantly more <br>
modular, spreading the complexity across the compiler and the interpreter. It <br>
will be possible to test the compiler separately from the interpreter, allowing <br>
for easier maintenance. We expect the frontend to become simpler and more <br>
maintainable after the AST walker is removed.<br>
<br>
The full implementation of the interpreter is expected to involve significant <br>
engineering effort. While development is in progress, an implementation of <br>
reduction rules is required in both the tree walker and interpreter, adding <br>
redundancy.<br>
<br>
Extensibility<br>
<br>
The interpreter should evolve alongside the language in the future, allowing for <br>
new features included in future standards to be supported. We refrain from <br>
performing any optimizations that would hinder the implementation of additional <br>
features, such as constexpr support for alloca and exception handling.<br>
<br>
Thanks for reading!<br>
<br>
Nandor Licker<br>
<br>
_______________________________________________<br>
cfe-dev mailing list<br>
<a href="mailto:cfe-dev@lists.llvm.org" target="_blank">cfe-dev@lists.llvm.org</a><br>
<a href="https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-dev" rel="noreferrer" target="_blank">https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-dev</a><br>
</blockquote></div></div>