New LDC feature: dynamic compilation

Ivan Butygin ivan.butygin at gmail.com
Mon Nov 13 19:04:16 UTC 2017


Main part of this feature is a new UDA `@dynamicCompile`.

You can mark with this attribute any function (including class 
methods and lambdas) and compilation and optimization of this 
function will be deferred to runtime.
Dynamic compiler will use instruction set available on host, so 
application can utilize the best available instructions without 
sacrificing users with old hardware.
You only need to mark top-level function with this UDA, compiler 
will also defer compilation for any function called from root 
with body available.
You need to explicitly compile `@dynamicCompile` functions before 
using any of them.

CompilerSettings settings;
settings.optLevel = 3; // -O3
compileDynamicCode(settings); // compile all dynamic functions

Second feature is `@dynamicCompileConst` variables.
You can mark any global non-thread local variable with this 
attribute.
They are treated as usual from static code but if they are 
treated as compile-time constants by optimizer when accessed from 
`@dynamicCompile` function.

Example:
`@dynamicCompileConst` __gshared simdSize;

`@dynamicCompile` void foo()
{
   if (4 == simdSize)
   {
     // SSE-otimized code
   }
   else if (8 == simdSize)
   {
     // AVX-optimized code
   }
}

...

simdSize = 4;
compileDynamicCode();

Optimizer will treat `simdSize` as constant and remove checks and 
not taken branches.

You shouldn't change these variables from dynamic code (this is 
UB and will probaly crash you)

And you need to recompile dynamic code with 
`compileDynamicCode(...)` if you want changes to these variables 
take effect in dynamic code.


These are highly experimental features so expect major bugs.

Known issues:
* There is debug hook to get final asm generated for 
`@dynamicCompile` function but it is disabled now (but you can 
still get original and optimized LLVM IR for them)
* Exceptions doesn't work on windows if there are dynamic 
functions in stack (they work on linux and osx).
* There are codegen issues on win32, use win64


More information about the Digitalmars-d-announce mailing list