Update CodecDataObjectGenerator documentation
[mdsal.git] / binding / mdsal-binding-dom-codec / src / main / java / org / opendaylight / mdsal / binding / dom / codec / impl / CodecDataObjectGenerator.java
index 4bee13e5efbf7a8224c3305932fd974ce95784a7..d8f1f367249269a5bed7e3ae5d12132de1eb2ac4 100644 (file)
@@ -16,9 +16,11 @@ import static org.opendaylight.mdsal.binding.dom.codec.impl.ByteBuddyUtils.invok
 import static org.opendaylight.mdsal.binding.dom.codec.impl.ByteBuddyUtils.putField;
 
 import com.google.common.base.MoreObjects.ToStringHelper;
-import com.google.common.base.Supplier;
 import com.google.common.collect.ImmutableMap;
 import com.google.common.collect.Maps;
+import java.lang.invoke.MethodHandles;
+import java.lang.invoke.MethodHandles.Lookup;
+import java.lang.invoke.VarHandle;
 import java.lang.reflect.Method;
 import java.util.ArrayList;
 import java.util.Arrays;
@@ -28,7 +30,6 @@ import java.util.Map;
 import java.util.Map.Entry;
 import java.util.Objects;
 import java.util.Optional;
-import java.util.concurrent.atomic.AtomicReferenceFieldUpdater;
 import net.bytebuddy.ByteBuddy;
 import net.bytebuddy.description.field.FieldDescription;
 import net.bytebuddy.description.method.MethodDescription;
@@ -52,8 +53,9 @@ import net.bytebuddy.implementation.bytecode.member.MethodVariableAccess;
 import net.bytebuddy.jar.asm.Label;
 import net.bytebuddy.jar.asm.MethodVisitor;
 import net.bytebuddy.jar.asm.Opcodes;
-import org.eclipse.jdt.annotation.NonNull;
 import org.eclipse.jdt.annotation.Nullable;
+import org.opendaylight.mdsal.binding.dom.codec.impl.ClassGeneratorBridge.LocalNameProvider;
+import org.opendaylight.mdsal.binding.dom.codec.impl.ClassGeneratorBridge.NodeContextSupplierProvider;
 import org.opendaylight.mdsal.binding.dom.codec.loader.CodecClassLoader;
 import org.opendaylight.mdsal.binding.dom.codec.loader.CodecClassLoader.ClassGenerator;
 import org.opendaylight.mdsal.binding.dom.codec.loader.CodecClassLoader.GeneratorResult;
@@ -66,9 +68,11 @@ import org.slf4j.LoggerFactory;
  *
  * <p>
  * Code generation here is probably more involved than usual mainly due to the fact we *really* want to express the
- * strong connection between a generated class and BindingCodecContext in terms of a true constant, which boils down to
- * {@code private static final NodeContextSupplier NCS}. Having such constants provides significant boost to JITs
- * ability to optimize code -- especially with inlining and constant propagation.
+ * strong connection between a generated class to the extent possible. In most cases (grouping-generated types) this
+ * involves one level of indirection, which is a safe approach. If we are dealing with a type generated outside of a
+ * grouping statement, though, we are guaranteed instantiation-invariance and hence can hard-wire to a runtime-constant
+ * {@link NodeContextSupplier} -- which  provides significant boost to JITs ability to optimize code -- especially with
+ * inlining and constant propagation.
  *
  * <p>
  * The accessor mapping performance is critical due to users typically not taking care of storing the results acquired
@@ -87,7 +91,7 @@ import org.slf4j.LoggerFactory;
  * we end up generating a class with the following layout:
  * <pre>
  *     public final class Foo$$$codecImpl extends CodecDataObject implements Foo {
- *         private static final AtomicRefereceFieldUpdater&lt;Foo$$$codecImpl, Object&gt; getBar$$$A;
+ *         private static final VarHandle getBar$$$V;
  *         private volatile Object getBar;
  *
  *         public Foo$$$codecImpl(NormalizedNodeContainer data) {
@@ -95,7 +99,7 @@ import org.slf4j.LoggerFactory;
  *         }
  *
  *         public Bar getBar() {
- *             return (Bar) codecMember(getBar$$$A, "bar");
+ *             return (Bar) codecMember(getBar$$$V, "bar");
  *         }
  *     }
  * </pre>
@@ -105,11 +109,13 @@ import org.slf4j.LoggerFactory;
  * single place in a maintainable form. The glue code is extremely light (~6 instructions), which is beneficial on both
  * sides of invocation:
  * - generated method can readily be inlined into the caller
- * - it forms a call site into which codeMember() can be inlined with AtomicReferenceFieldUpdater being constant
+ * - it forms a call site into which codeMember() can be inlined with VarHandle being constant
  *
  * <p>
- * The second point is important here, as it allows the invocation logic around AtomicRefereceFieldUpdater to completely
- * disappear, becoming synonymous with operations of a volatile field.
+ * The second point is important here, as it allows the invocation logic around VarHandle to completely disappear,
+ * becoming synonymous with operations on a field. Even though the field itself is declared as volatile, it is only ever
+ * accessed through helper method using VarHandles -- and those helpers are using relaxed field ordering
+ * of {@code getAcquire()}/{@code setRelease()} memory semantics.
  *
  * <p>
  * Furthermore there are distinct {@code codecMember} methods, each of which supports a different invocation style:
@@ -136,17 +142,18 @@ import org.slf4j.LoggerFactory;
  * We take a different approach here, which takes advantage of the fact we are in control of both code generation (here)
  * and class loading (in {@link CodecClassLoader}). The process is performed in four steps:
  * <ul>
- * <li>During code generation, the context fields are pointed towards {@link CodecDataObjectBridge#resolve(String)} and
- *     {@link CodecDataObjectBridge#resolveKey(String)} methods, which are public and static, hence perfectly usable
+ * <li>During code generation, the context fields are pointed towards
+ *     {@link ClassGeneratorBridge#resolveNodeContextSupplier(String)} and
+ *     {@link ClassGeneratorBridge#resolveKey(String)} methods, which are public and static, hence perfectly usable
  *     in the context of a class initializer.</li>
  * <li>During class loading of generated byte code, the original instance of the generator is called to wrap the actual
  *     class loading operation. At this point the generator installs itself as the current generator for this thread via
- *     {@link CodecDataObjectBridge#setup(CodecDataObjectGenerator)} and allows the class to be loaded.
+ *     {@link ClassGeneratorBridge#setup(CodecDataObjectGenerator)} and allows the class to be loaded.
  * <li>After the class has been loaded, but before the call returns, we will force the class to initialize, at which
- *     point the static invocations will be redirect to {@link #resolve(String)} and {@link #resolveKey(String)}
- *     methods, thus initializing the fields to the intended constants.</li>
+ *     point the static invocations will be redirect to {@link #resolveNodeContextSupplier(String)} and
+ *     {@link #resolveKey(String)} methods, thus initializing the fields to the intended constants.</li>
  * <li>Before returning from the class loading call, the generator will detach itself via
- *     {@link CodecDataObjectBridge#tearDown(CodecDataObjectGenerator)}.</li>
+ *     {@link ClassGeneratorBridge#tearDown(CodecDataObjectGenerator)}.</li>
  * </ul>
  *
  * <p>
@@ -154,11 +161,14 @@ import org.slf4j.LoggerFactory;
  * block runs with the class loading lock for this FQCN and the reference is not leaked until the process completes.
  */
 abstract class CodecDataObjectGenerator<T extends CodecDataObject<?>> implements ClassGenerator<T> {
-    // Not reusable defintion: we can inline NodeContextSuppliers without a problem
-    static final class Fixed<T extends CodecDataObject<?>> extends CodecDataObjectGenerator<T> {
+    // Not reusable definition: we can inline NodeContextSuppliers without a problem
+    // FIXME: 6.0.0: wire this implementation, which requires that BindingRuntimeTypes provides information about types
+    //               being genenerated from within a grouping
+    private static final class Fixed<T extends CodecDataObject<?>> extends CodecDataObjectGenerator<T>
+            implements NodeContextSupplierProvider<T> {
         private final ImmutableMap<Method, NodeContextSupplier> properties;
 
-        private Fixed(final Builder<?> template, final ImmutableMap<Method, NodeContextSupplier> properties,
+        Fixed(final Builder<?> template, final ImmutableMap<Method, NodeContextSupplier> properties,
                 final @Nullable Method keyMethod) {
             super(template, keyMethod);
             this.properties = requireNonNull(properties);
@@ -183,32 +193,7 @@ abstract class CodecDataObjectGenerator<T extends CodecDataObject<?>> implements
         }
 
         @Override
-        public Class<T> customizeLoading(final @NonNull Supplier<Class<T>> loader) {
-            final Fixed<?> prev = CodecDataObjectBridge.setup(this);
-            try {
-                final Class<T> result = loader.get();
-
-                /*
-                 * This a bit of magic to support NodeContextSupplier constants. These constants need to be resolved
-                 * while we have the information needed to find them -- that information is being held in this instance
-                 * and we leak it to a thread-local variable held by CodecDataObjectBridge.
-                 *
-                 * By default the JVM will defer class initialization to first use, which unfortunately is too late for
-                 * us, and hence we need to force class to initialize.
-                 */
-                try {
-                    Class.forName(result.getName(), true, result.getClassLoader());
-                } catch (ClassNotFoundException e) {
-                    throw new LinkageError("Failed to find newly-defined " + result, e);
-                }
-
-                return result;
-            } finally {
-                CodecDataObjectBridge.tearDown(prev);
-            }
-        }
-
-        @NonNull NodeContextSupplier resolve(final @NonNull String methodName) {
+        public NodeContextSupplier resolveNodeContextSupplier(final String methodName) {
             final Optional<Entry<Method, NodeContextSupplier>> found = properties.entrySet().stream()
                     .filter(entry -> methodName.equals(entry.getKey().getName())).findAny();
             verify(found.isPresent(), "Failed to find property for %s in %s", methodName, this);
@@ -217,12 +202,12 @@ abstract class CodecDataObjectGenerator<T extends CodecDataObject<?>> implements
     }
 
     // Reusable definition: we have to rely on context lookups
-    private static final class Reusable<T extends CodecDataObject<?>> extends CodecDataObjectGenerator<T> {
+    private static final class Reusable<T extends CodecDataObject<?>> extends CodecDataObjectGenerator<T>
+            implements LocalNameProvider<T> {
         private final ImmutableMap<Method, ValueNodeCodecContext> simpleProperties;
         private final Map<Method, Class<?>> daoProperties;
 
-        private Reusable(final Builder<?> template,
-                final ImmutableMap<Method, ValueNodeCodecContext> simpleProperties,
+        Reusable(final Builder<?> template, final ImmutableMap<Method, ValueNodeCodecContext> simpleProperties,
                 final Map<Method, Class<?>> daoProperties, final @Nullable Method keyMethod) {
             super(template, keyMethod);
             this.simpleProperties = requireNonNull(simpleProperties);
@@ -232,14 +217,12 @@ abstract class CodecDataObjectGenerator<T extends CodecDataObject<?>> implements
         @Override
         Builder<T> generateGetters(final Builder<T> builder) {
             Builder<T> tmp = builder;
-            for (Entry<Method, ValueNodeCodecContext> entry : simpleProperties.entrySet()) {
-                final Method method = entry.getKey();
+            for (Method method : simpleProperties.keySet()) {
                 LOG.trace("Generating for simple method {}", method);
                 final String methodName = method.getName();
                 final TypeDescription retType = TypeDescription.ForLoadedType.of(method.getReturnType());
                 tmp = tmp.defineMethod(methodName, retType, PUB_FINAL).intercept(
-                    new SimpleGetterMethodImplementation(methodName, retType,
-                        entry.getValue().getSchema().getQName().getLocalName()));
+                    new SimpleGetterMethodImplementation(methodName, retType));
             }
             for (Entry<Method, Class<?>> entry : daoProperties.entrySet()) {
                 final Method method = entry.getKey();
@@ -260,6 +243,14 @@ abstract class CodecDataObjectGenerator<T extends CodecDataObject<?>> implements
             ret.addAll(daoProperties.keySet());
             return ret;
         }
+
+        @Override
+        public String resolveLocalName(final String methodName) {
+            final Optional<Entry<Method, ValueNodeCodecContext>> found = simpleProperties.entrySet().stream()
+                    .filter(entry -> methodName.equals(entry.getKey().getName())).findAny();
+            verify(found.isPresent(), "Failed to find property for %s in %s", methodName, this);
+            return found.get().getValue().getSchema().getQName().getLocalName();
+        }
     }
 
     private static final Logger LOG = LoggerFactory.getLogger(CodecDataObjectGenerator.class);
@@ -293,7 +284,7 @@ abstract class CodecDataObjectGenerator<T extends CodecDataObject<?>> implements
     private final Builder<?> template;
     private final Method keyMethod;
 
-    private CodecDataObjectGenerator(final Builder<?> template, final @Nullable Method keyMethod) {
+    CodecDataObjectGenerator(final Builder<?> template, final @Nullable Method keyMethod) {
         this.template = requireNonNull(template);
         this.keyMethod = keyMethod;
     }
@@ -407,11 +398,12 @@ abstract class CodecDataObjectGenerator<T extends CodecDataObject<?>> implements
     }
 
     private abstract static class AbstractMethodImplementation implements Implementation {
-        private static final Generic BB_ARFU = TypeDefinition.Sort.describe(AtomicReferenceFieldUpdater.class);
+        private static final Generic BB_HANDLE = TypeDefinition.Sort.describe(VarHandle.class);
         private static final Generic BB_OBJECT = TypeDefinition.Sort.describe(Object.class);
         private static final StackManipulation OBJECT_CLASS = ClassConstant.of(TypeDescription.OBJECT);
-        private static final StackManipulation ARFU_NEWUPDATER = invokeMethod(AtomicReferenceFieldUpdater.class,
-            "newUpdater", Class.class, Class.class, String.class);
+        private static final StackManipulation LOOKUP = invokeMethod(MethodHandles.class, "lookup");
+        private static final StackManipulation FIND_VAR_HANDLE = invokeMethod(Lookup.class,
+            "findVarHandle", Class.class, String.class, Class.class);
 
         static final int PRIV_CONST = Opcodes.ACC_PRIVATE | Opcodes.ACC_STATIC | Opcodes.ACC_FINAL
                 | Opcodes.ACC_SYNTHETIC;
@@ -420,36 +412,38 @@ abstract class CodecDataObjectGenerator<T extends CodecDataObject<?>> implements
         final TypeDescription retType;
         // getFoo
         final String methodName;
-        // getFoo$$$A
-        final String arfuName;
+        // getFoo$$$V
+        final String handleName;
 
         AbstractMethodImplementation(final String methodName, final TypeDescription retType) {
             this.methodName = requireNonNull(methodName);
             this.retType = requireNonNull(retType);
-            this.arfuName = methodName + "$$$A";
+            this.handleName = methodName + "$$$V";
         }
 
         @Override
         public InstrumentedType prepare(final InstrumentedType instrumentedType) {
             final InstrumentedType tmp = instrumentedType
-                    // private static final AtomicReferenceFieldUpdater<This, Object> getFoo$$$A;
-                    .withField(new FieldDescription.Token(arfuName, PRIV_CONST, BB_ARFU))
+                    // private static final VarHandle getFoo$$$V;
+                    .withField(new FieldDescription.Token(handleName, PRIV_CONST, BB_HANDLE))
                     // private volatile Object getFoo;
                     .withField(new FieldDescription.Token(methodName, PRIV_VOLATILE, BB_OBJECT));
 
             return tmp.withInitializer(new ByteCodeAppender.Simple(
-                // getFoo$$$A = AtomicReferenceFieldUpdater.newUpdater(This.class, Object.class, "getFoo");
+                // TODO: acquiring lookup is expensive, we should share it across all initialization
+                // getFoo$$$V = MethodHandles.lookup().findVarHandle(This.class, "getFoo", Object.class);
+                LOOKUP,
                 ClassConstant.of(tmp),
-                OBJECT_CLASS,
                 new TextConstant(methodName),
-                ARFU_NEWUPDATER,
-                putField(tmp, arfuName)));
+                OBJECT_CLASS,
+                FIND_VAR_HANDLE,
+                putField(tmp, handleName)));
         }
     }
 
     private static final class KeyMethodImplementation extends AbstractMethodImplementation {
         private static final StackManipulation CODEC_KEY = invokeMethod(CodecDataObject.class,
-            "codecKey", AtomicReferenceFieldUpdater.class);
+            "codecKey", VarHandle.class);
 
         KeyMethodImplementation(final String methodName, final TypeDescription retType) {
             super(methodName, retType);
@@ -459,35 +453,58 @@ abstract class CodecDataObjectGenerator<T extends CodecDataObject<?>> implements
         public ByteCodeAppender appender(final Target implementationTarget) {
             final TypeDescription instrumentedType = implementationTarget.getInstrumentedType();
             return new ByteCodeAppender.Simple(
-                // return (FooType) codecKey(getFoo$$$A);
+                // return (FooType) codecKey(getFoo$$$V);
                 THIS,
-                getField(instrumentedType, arfuName),
+                getField(instrumentedType, handleName),
                 CODEC_KEY,
                 TypeCasting.to(retType),
                 MethodReturn.REFERENCE);
         }
     }
 
+    /*
+     * A simple leaf method, which looks up child by a String constant. This is slightly more complicated because we
+     * want to make sure we are using the same String instance as the one stored in associated DataObjectCodecContext,
+     * so that during lookup we perform an identity check instead of comparing content -- speeding things up as well
+     * as minimizing footprint. Since that string is not guaranteed to be interned in the String Pool, we cannot rely
+     * on the constant pool entry to resolve to the same object.
+     */
     private static final class SimpleGetterMethodImplementation extends AbstractMethodImplementation {
         private static final StackManipulation CODEC_MEMBER = invokeMethod(CodecDataObject.class,
-            "codecMember", AtomicReferenceFieldUpdater.class, String.class);
+            "codecMember", VarHandle.class, String.class);
+        private static final StackManipulation BRIDGE_RESOLVE = invokeMethod(ClassGeneratorBridge.class,
+            "resolveLocalName", String.class);
+        private static final Generic BB_STRING = TypeDefinition.Sort.describe(String.class);
 
-        private final String localName;
+        // getFoo$$$S
+        private final String stringName;
 
-        SimpleGetterMethodImplementation(final String methodName, final TypeDescription retType,
-                final String localName) {
+        SimpleGetterMethodImplementation(final String methodName, final TypeDescription retType) {
             super(methodName, retType);
-            this.localName = requireNonNull(localName);
+            this.stringName = methodName + "$$$S";
+        }
+
+        @Override
+        public InstrumentedType prepare(final InstrumentedType instrumentedType) {
+            final InstrumentedType tmp = super.prepare(instrumentedType)
+                    // private static final String getFoo$$$S;
+                    .withField(new FieldDescription.Token(stringName, PRIV_CONST, BB_STRING));
+
+            return tmp.withInitializer(new ByteCodeAppender.Simple(
+                // getFoo$$$S = CodecDataObjectBridge.resolveString("getFoo");
+                new TextConstant(methodName),
+                BRIDGE_RESOLVE,
+                putField(tmp, stringName)));
         }
 
         @Override
         public ByteCodeAppender appender(final Target implementationTarget) {
             final TypeDescription instrumentedType = implementationTarget.getInstrumentedType();
             return new ByteCodeAppender.Simple(
-                // return (FooType) codecMember(getFoo$$$A, "foo");
+                // return (FooType) codecMember(getFoo$$$V, getFoo$$$S);
                 THIS,
-                getField(instrumentedType, arfuName),
-                new TextConstant(localName),
+                getField(instrumentedType, handleName),
+                getField(instrumentedType, stringName),
                 CODEC_MEMBER,
                 TypeCasting.to(retType),
                 MethodReturn.REFERENCE);
@@ -496,7 +513,7 @@ abstract class CodecDataObjectGenerator<T extends CodecDataObject<?>> implements
 
     private static final class StructuredGetterMethodImplementation extends AbstractMethodImplementation {
         private static final StackManipulation CODEC_MEMBER = invokeMethod(CodecDataObject.class,
-            "codecMember", AtomicReferenceFieldUpdater.class, Class.class);
+            "codecMember", VarHandle.class, Class.class);
 
         private final Class<?> bindingClass;
 
@@ -510,9 +527,9 @@ abstract class CodecDataObjectGenerator<T extends CodecDataObject<?>> implements
         public ByteCodeAppender appender(final Target implementationTarget) {
             final TypeDescription instrumentedType = implementationTarget.getInstrumentedType();
             return new ByteCodeAppender.Simple(
-                // return (FooType) codecMember(getFoo$$$A, FooType.class);
+                // return (FooType) codecMember(getFoo$$$V, FooType.class);
                 THIS,
-                getField(instrumentedType, arfuName),
+                getField(instrumentedType, handleName),
                 ClassConstant.of(TypeDefinition.Sort.describe(bindingClass).asErasure()),
                 CODEC_MEMBER,
                 TypeCasting.to(retType),
@@ -522,9 +539,9 @@ abstract class CodecDataObjectGenerator<T extends CodecDataObject<?>> implements
 
     private static final class SupplierGetterMethodImplementation extends AbstractMethodImplementation {
         private static final StackManipulation CODEC_MEMBER = invokeMethod(CodecDataObject.class,
-            "codecMember", AtomicReferenceFieldUpdater.class, NodeContextSupplier.class);
-        private static final StackManipulation BRIDGE_RESOLVE = invokeMethod(CodecDataObjectBridge.class,
-            "resolve", String.class);
+            "codecMember", VarHandle.class, NodeContextSupplier.class);
+        private static final StackManipulation BRIDGE_RESOLVE = invokeMethod(ClassGeneratorBridge.class,
+            "resolveNodeContextSupplier", String.class);
         private static final Generic BB_NCS = TypeDefinition.Sort.describe(NodeContextSupplier.class);
 
         // getFoo$$$C
@@ -552,9 +569,9 @@ abstract class CodecDataObjectGenerator<T extends CodecDataObject<?>> implements
         public ByteCodeAppender appender(final Target implementationTarget) {
             final TypeDescription instrumentedType = implementationTarget.getInstrumentedType();
             return new ByteCodeAppender.Simple(
-                // return (FooType) codecMember(getFoo$$$A, getFoo$$$C);
+                // return (FooType) codecMember(getFoo$$$V, getFoo$$$C);
                 THIS,
-                getField(instrumentedType, arfuName),
+                getField(instrumentedType, handleName),
                 getField(instrumentedType, contextName),
                 CODEC_MEMBER,
                 TypeCasting.to(retType),