Bump byte-buddy to 1.14.11
[mdsal.git] / binding / mdsal-binding-dom-codec / src / main / java / org / opendaylight / mdsal / binding / dom / codec / impl / CodecDataObjectGenerator.java
index c965a087a93b2bd05bec8a32b7305064893118df..19f31386fa760760d15b3d1af6b8f6dcf7ab37c7 100644 (file)
@@ -10,29 +10,21 @@ package org.opendaylight.mdsal.binding.dom.codec.impl;
 import static com.google.common.base.Verify.verify;
 import static com.google.common.base.Verify.verifyNotNull;
 import static java.util.Objects.requireNonNull;
-import static org.opendaylight.mdsal.binding.dom.codec.impl.ByteBuddyUtils.THIS;
+import static net.bytebuddy.implementation.bytecode.member.MethodVariableAccess.loadThis;
 import static org.opendaylight.mdsal.binding.dom.codec.impl.ByteBuddyUtils.getField;
 import static org.opendaylight.mdsal.binding.dom.codec.impl.ByteBuddyUtils.invokeMethod;
 import static org.opendaylight.mdsal.binding.dom.codec.impl.ByteBuddyUtils.putField;
 
-import com.google.common.base.MoreObjects.ToStringHelper;
 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;
-import java.util.Comparator;
-import java.util.List;
 import java.util.Map;
 import java.util.Map.Entry;
-import java.util.Objects;
 import java.util.Optional;
 import net.bytebuddy.ByteBuddy;
 import net.bytebuddy.description.field.FieldDescription;
-import net.bytebuddy.description.method.MethodDescription;
 import net.bytebuddy.description.type.TypeDefinition;
 import net.bytebuddy.description.type.TypeDescription;
 import net.bytebuddy.description.type.TypeDescription.ForLoadedType;
@@ -40,27 +32,21 @@ import net.bytebuddy.description.type.TypeDescription.Generic;
 import net.bytebuddy.dynamic.DynamicType.Builder;
 import net.bytebuddy.dynamic.scaffold.InstrumentedType;
 import net.bytebuddy.implementation.Implementation;
-import net.bytebuddy.implementation.Implementation.Context;
-import net.bytebuddy.implementation.bytecode.Addition;
 import net.bytebuddy.implementation.bytecode.ByteCodeAppender;
-import net.bytebuddy.implementation.bytecode.Multiplication;
 import net.bytebuddy.implementation.bytecode.StackManipulation;
 import net.bytebuddy.implementation.bytecode.assign.TypeCasting;
 import net.bytebuddy.implementation.bytecode.constant.ClassConstant;
-import net.bytebuddy.implementation.bytecode.constant.IntegerConstant;
 import net.bytebuddy.implementation.bytecode.constant.TextConstant;
 import net.bytebuddy.implementation.bytecode.member.MethodReturn;
 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.Nullable;
+import org.opendaylight.mdsal.binding.dom.codec.impl.ClassGeneratorBridge.CodecContextSupplierProvider;
 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;
-import org.opendaylight.yangtools.yang.binding.DataObject;
+import org.opendaylight.mdsal.binding.loader.BindingClassLoader;
+import org.opendaylight.mdsal.binding.loader.BindingClassLoader.ClassGenerator;
+import org.opendaylight.mdsal.binding.loader.BindingClassLoader.GeneratorResult;
+import org.opendaylight.yangtools.yang.binding.contract.Naming;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
@@ -72,7 +58,7 @@ import org.slf4j.LoggerFactory;
  * 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
+ * {@link CodecContextSupplier} -- which  provides significant boost to JITs ability to optimize code -- especially with
  * inlining and constant propagation.
  *
  * <p>
@@ -95,7 +81,7 @@ import org.slf4j.LoggerFactory;
  *         private static final VarHandle getBar$$$V;
  *         private volatile Object getBar;
  *
- *         public Foo$$$codecImpl(NormalizedNodeContainer data) {
+ *         public Foo$$$codecImpl(DistinctNodeContainer data) {
  *             super(data);
  *         }
  *
@@ -143,17 +129,17 @@ import org.slf4j.LoggerFactory;
  *
  * <p>
  * 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:
+ * and class loading (in {@link BindingClassLoader}). The process is performed in four steps:
  * <ul>
  * <li>During code generation, the context fields are pointed towards
- *     {@link ClassGeneratorBridge#resolveNodeContextSupplier(String)} and
+ *     {@link ClassGeneratorBridge#resolveCodecContextSupplier(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 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 redirected to {@link #resolveNodeContextSupplier(String)} and
+ *     point the static invocations will be redirected to {@link #resolveCodecContextSupplier(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 ClassGeneratorBridge#tearDown(CodecDataObjectGenerator)}.</li>
@@ -165,13 +151,13 @@ import org.slf4j.LoggerFactory;
  */
 abstract class CodecDataObjectGenerator<T extends CodecDataObject<?>> implements ClassGenerator<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 generated from within a grouping
+    // FIXME: MDSAL-443: wire this implementation, which requires that BindingRuntimeTypes provides information about
+    //                   types being generated from within a grouping
     private static final class Fixed<T extends CodecDataObject<?>> extends CodecDataObjectGenerator<T>
-            implements NodeContextSupplierProvider<T> {
-        private final ImmutableMap<Method, NodeContextSupplier> properties;
+            implements CodecContextSupplierProvider<T> {
+        private final ImmutableMap<Method, CodecContextSupplier> properties;
 
-        Fixed(final TypeDescription superClass, final ImmutableMap<Method, NodeContextSupplier> properties,
+        Fixed(final TypeDescription superClass, final ImmutableMap<Method, CodecContextSupplier> properties,
                 final @Nullable Method keyMethod) {
             super(superClass, keyMethod);
             this.properties = requireNonNull(properties);
@@ -183,7 +169,7 @@ abstract class CodecDataObjectGenerator<T extends CodecDataObject<?>> implements
             for (Method method : properties.keySet()) {
                 LOG.trace("Generating for fixed method {}", method);
                 final String methodName = method.getName();
-                final TypeDescription retType = TypeDescription.ForLoadedType.of(method.getReturnType());
+                final TypeDescription retType = ForLoadedType.of(method.getReturnType());
                 tmp = tmp.defineMethod(methodName, retType, PUB_FINAL).intercept(
                     new SupplierGetterMethodImplementation(methodName, retType));
             }
@@ -191,16 +177,11 @@ abstract class CodecDataObjectGenerator<T extends CodecDataObject<?>> implements
         }
 
         @Override
-        ArrayList<Method> getterMethods() {
-            return new ArrayList<>(properties.keySet());
-        }
-
-        @Override
-        public NodeContextSupplier resolveNodeContextSupplier(final String methodName) {
-            final Optional<Entry<Method, NodeContextSupplier>> found = properties.entrySet().stream()
+        public CodecContextSupplier resolveCodecContextSupplier(final String methodName) {
+            final Optional<Entry<Method, CodecContextSupplier>> 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);
-            return verifyNotNull(found.get().getValue());
+            return verifyNotNull(found.orElseThrow().getValue());
         }
     }
 
@@ -208,10 +189,10 @@ abstract class CodecDataObjectGenerator<T extends CodecDataObject<?>> implements
     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 final Map<Class<?>, PropertyInfo> daoProperties;
 
         Reusable(final TypeDescription superClass, final ImmutableMap<Method, ValueNodeCodecContext> simpleProperties,
-                final Map<Method, Class<?>> daoProperties, final @Nullable Method keyMethod) {
+                final Map<Class<?>, PropertyInfo> daoProperties, final @Nullable Method keyMethod) {
             super(superClass, keyMethod);
             this.simpleProperties = requireNonNull(simpleProperties);
             this.daoProperties = requireNonNull(daoProperties);
@@ -223,54 +204,45 @@ abstract class CodecDataObjectGenerator<T extends CodecDataObject<?>> implements
             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());
+                final TypeDescription retType = ForLoadedType.of(method.getReturnType());
                 tmp = tmp.defineMethod(methodName, retType, PUB_FINAL).intercept(
                     new SimpleGetterMethodImplementation(methodName, retType));
             }
-            for (Entry<Method, Class<?>> entry : daoProperties.entrySet()) {
-                final Method method = entry.getKey();
+            for (Entry<Class<?>, PropertyInfo> entry : daoProperties.entrySet()) {
+                final PropertyInfo info = entry.getValue();
+                final Method method = info.getterMethod();
                 LOG.trace("Generating for structured method {}", method);
                 final String methodName = method.getName();
-                final TypeDescription retType = TypeDescription.ForLoadedType.of(method.getReturnType());
+                final TypeDescription retType = ForLoadedType.of(method.getReturnType());
                 tmp = tmp.defineMethod(methodName, retType, PUB_FINAL).intercept(
-                    new StructuredGetterMethodImplementation(methodName, retType, entry.getValue()));
+                        new StructuredGetterMethodImplementation(methodName, retType, entry.getKey()));
+
+                if (info instanceof PropertyInfo.GetterAndNonnull orEmpty) {
+                    final String nonnullName = orEmpty.nonnullMethod().getName();
+                    tmp = tmp.defineMethod(nonnullName, retType, PUB_FINAL).intercept(
+                        new NonnullMethodImplementation(nonnullName, retType, entry.getKey(), method));
+                }
             }
 
             return tmp;
         }
 
-        @Override
-        ArrayList<Method> getterMethods() {
-            final ArrayList<Method> ret = new ArrayList<>(simpleProperties.size() + daoProperties.size());
-            ret.addAll(simpleProperties.keySet());
-            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();
+            return found.orElseThrow().getValue().getSchema().getQName().getLocalName();
         }
     }
 
     private static final Logger LOG = LoggerFactory.getLogger(CodecDataObjectGenerator.class);
     private static final Generic BB_BOOLEAN = TypeDefinition.Sort.describe(boolean.class);
-    private static final Generic BB_DATAOBJECT = TypeDefinition.Sort.describe(DataObject.class);
-    private static final Generic BB_HELPER = TypeDefinition.Sort.describe(ToStringHelper.class);
+    private static final Generic BB_OBJECT = TypeDefinition.Sort.describe(Object.class);
     private static final Generic BB_INT = TypeDefinition.Sort.describe(int.class);
+    private static final Generic BB_STRING = TypeDefinition.Sort.describe(String.class);
     private static final TypeDescription BB_CDO = ForLoadedType.of(CodecDataObject.class);
     private static final TypeDescription BB_ACDO = ForLoadedType.of(AugmentableCodecDataObject.class);
-    private static final Comparator<Method> METHOD_BY_ALPHABET = Comparator.comparing(Method::getName);
-
-    private static final StackManipulation ARRAYS_EQUALS = invokeMethod(Arrays.class, "equals",
-        byte[].class, byte[].class);
-    private static final StackManipulation OBJECTS_EQUALS = invokeMethod(Objects.class, "equals",
-        Object.class, Object.class);
-    private static final StackManipulation HELPER_ADD = invokeMethod(ToStringHelper.class, "add",
-        String.class, Object.class);
 
     private static final StackManipulation FIRST_ARG_REF = MethodVariableAccess.REFERENCE.loadFrom(1);
 
@@ -287,120 +259,97 @@ abstract class CodecDataObjectGenerator<T extends CodecDataObject<?>> implements
         this.keyMethod = keyMethod;
     }
 
-    static <D extends DataObject, T extends CodecDataObject<T>> Class<T> generate(final CodecClassLoader loader,
-            final Class<D> bindingInterface, final ImmutableMap<Method, ValueNodeCodecContext> simpleProperties,
-            final Map<Method, Class<?>> daoProperties, final Method keyMethod) {
-        return loader.generateClass(bindingInterface, "codecImpl",
+    static <T extends CodecDataObject<T>> Class<T> generate(final BindingClassLoader loader,
+            final Class<?> bindingInterface, final ImmutableMap<Method, ValueNodeCodecContext> simpleProperties,
+            final Map<Class<?>, PropertyInfo> daoProperties, final Method keyMethod) {
+        return CodecPackage.CODEC.generateClass(loader, bindingInterface,
             new Reusable<>(BB_CDO, simpleProperties, daoProperties, keyMethod));
     }
 
-    static <D extends DataObject, T extends CodecDataObject<T>> Class<T> generateAugmentable(
-            final CodecClassLoader loader, final Class<D> bindingInterface,
-            final ImmutableMap<Method, ValueNodeCodecContext> simpleProperties,
-            final Map<Method, Class<?>> daoProperties, final Method keyMethod) {
-        return loader.generateClass(bindingInterface, "codecImpl",
+    static <T extends CodecDataObject<T>> Class<T> generateAugmentable(final BindingClassLoader loader,
+            final Class<?> bindingInterface, final ImmutableMap<Method, ValueNodeCodecContext> simpleProperties,
+            final Map<Class<?>, PropertyInfo> daoProperties, final Method keyMethod) {
+        return CodecPackage.CODEC.generateClass(loader, bindingInterface,
             new Reusable<>(BB_ACDO, simpleProperties, daoProperties, keyMethod));
     }
 
     @Override
-    public final GeneratorResult<T> generateClass(final CodecClassLoader loeader, final String fqcn,
+    public final GeneratorResult<T> generateClass(final BindingClassLoader loader, final String fqcn,
             final Class<?> bindingInterface) {
         LOG.trace("Generating class {}", fqcn);
 
         final Generic bindingDef = TypeDefinition.Sort.describe(bindingInterface);
         @SuppressWarnings("unchecked")
         Builder<T> builder = (Builder<T>) BB.subclass(Generic.Builder.parameterizedType(superClass, bindingDef).build())
-            .visit(ByteBuddyUtils.computeFrames()).name(fqcn).implement(bindingDef);
+            .name(fqcn).implement(bindingDef);
 
         builder = generateGetters(builder);
 
         if (keyMethod != null) {
             LOG.trace("Generating for key {}", keyMethod);
             final String methodName = keyMethod.getName();
-            final TypeDescription retType = TypeDescription.ForLoadedType.of(keyMethod.getReturnType());
+            final TypeDescription retType = ForLoadedType.of(keyMethod.getReturnType());
             builder = builder.defineMethod(methodName, retType, PUB_FINAL).intercept(
                 new KeyMethodImplementation(methodName, retType));
         }
 
-        // Index all property methods, turning them into "getFoo()" invocations, retaining order. We will be using
-        // those invocations in each of the three methods. Note that we do not glue the invocations to 'this', as we
-        // will be invoking them on 'other' in codecEquals()
-        final ArrayList<Method> properties = getterMethods();
-        // Make sure properties are alpha-sorted
-        properties.sort(METHOD_BY_ALPHABET);
-        final ImmutableMap<StackManipulation, Method> methods = Maps.uniqueIndex(properties,
-            ByteBuddyUtils::invokeMethod);
-
         // Final bits:
         return GeneratorResult.of(builder
                 // codecHashCode() ...
                 .defineMethod("codecHashCode", BB_INT, PROT_FINAL)
-                .intercept(new Implementation.Simple(new CodecHashCode(methods)))
-                // ... codecEquals() ...
-                .defineMethod("codecEquals", BB_BOOLEAN, PROT_FINAL).withParameter(BB_DATAOBJECT)
-                .intercept(codecEquals(methods))
-                // ... and codecFillToString() ...
-                .defineMethod("codecFillToString", BB_HELPER, PROT_FINAL).withParameter(BB_HELPER)
-                .intercept(codecFillToString(methods))
+                .intercept(codecHashCode(bindingInterface))
+                // ... equals(Object) ...
+                .defineMethod("codecEquals", BB_BOOLEAN, PROT_FINAL).withParameter(BB_OBJECT)
+                .intercept(codecEquals(bindingInterface))
+                // ... toString() ...
+                .defineMethod("toString", BB_STRING, PUB_FINAL)
+                .intercept(toString(bindingInterface))
                 // ... and build it
                 .make());
     }
 
     abstract Builder<T> generateGetters(Builder<T> builder);
 
-    abstract ArrayList<Method> getterMethods();
-
-    private static Implementation codecEquals(final ImmutableMap<StackManipulation, Method> properties) {
-        // Label for 'return false;'
-        final Label falseLabel = new Label();
-        // Condition for 'if (!...)'
-        final StackManipulation ifFalse = ByteBuddyUtils.ifEq(falseLabel);
-
-        final List<StackManipulation> manipulations = new ArrayList<>(properties.size() * 6 + 5);
-        for (Entry<StackManipulation, Method> entry : properties.entrySet()) {
-            // if (!java.util.(Objects|Arrays).equals(getFoo(), other.getFoo())) {
-            //     return false;
-            // }
-            manipulations.add(THIS);
-            manipulations.add(entry.getKey());
-            manipulations.add(FIRST_ARG_REF);
-            manipulations.add(entry.getKey());
-            manipulations.add(entry.getValue().getReturnType().isArray() ? ARRAYS_EQUALS : OBJECTS_EQUALS);
-            manipulations.add(ifFalse);
-        }
+    private static Implementation codecHashCode(final Class<?> bindingInterface) {
+        return new Implementation.Simple(
+            // return Foo.bindingHashCode(this);
+            loadThis(),
+            invokeMethod(bindingInterface, Naming.BINDING_HASHCODE_NAME, bindingInterface),
+            MethodReturn.INTEGER);
+    }
 
-        // return true;
-        manipulations.add(IntegerConstant.ONE);
-        manipulations.add(MethodReturn.INTEGER);
-        // L0: return false;
-        manipulations.add(ByteBuddyUtils.markLabel(falseLabel));
-        manipulations.add(IntegerConstant.ZERO);
-        manipulations.add(MethodReturn.INTEGER);
+    private static Implementation codecEquals(final Class<?> bindingInterface) {
+        return new Implementation.Simple(
+            // return Foo.bindingEquals(this, obj);
+            loadThis(),
+            FIRST_ARG_REF,
+            invokeMethod(bindingInterface, Naming.BINDING_EQUALS_NAME, bindingInterface, Object.class),
+            MethodReturn.INTEGER);
+    }
 
-        return new Implementation.Simple(manipulations.toArray(new StackManipulation[0]));
+    private static Implementation toString(final Class<?> bindingInterface) {
+        return new Implementation.Simple(
+            // return Foo.bindingToString(this);
+            loadThis(),
+            invokeMethod(bindingInterface, Naming.BINDING_TO_STRING_NAME, bindingInterface),
+            MethodReturn.REFERENCE);
     }
 
-    private static Implementation codecFillToString(final ImmutableMap<StackManipulation, Method> properties) {
-        final List<StackManipulation> manipulations = new ArrayList<>(properties.size() * 4 + 2);
-        // push 'return helper' to stack...
-        manipulations.add(FIRST_ARG_REF);
-        for (Entry<StackManipulation, Method> entry : properties.entrySet()) {
-            // .add("getFoo", getFoo())
-            manipulations.add(new TextConstant(entry.getValue().getName()));
-            manipulations.add(THIS);
-            manipulations.add(entry.getKey());
-            manipulations.add(HELPER_ADD);
-        }
-        // ... execute 'return helper'
-        manipulations.add(MethodReturn.REFERENCE);
+    private abstract static class AbstractMethodImplementation implements Implementation {
+        final TypeDescription retType;
+        // getFoo, usually
+        final String methodName;
 
-        return new Implementation.Simple(manipulations.toArray(new StackManipulation[0]));
+        AbstractMethodImplementation(final String methodName, final TypeDescription retType) {
+            this.methodName = requireNonNull(methodName);
+            this.retType = requireNonNull(retType);
+        }
     }
 
-    private abstract static class AbstractMethodImplementation implements Implementation {
+    private abstract static class AbstractCachedMethodImplementation extends AbstractMethodImplementation {
         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 OBJECT_CLASS = ClassConstant.of(ForLoadedType.of(Object.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);
@@ -409,16 +358,12 @@ abstract class CodecDataObjectGenerator<T extends CodecDataObject<?>> implements
                 | Opcodes.ACC_SYNTHETIC;
         private static final int PRIV_VOLATILE = Opcodes.ACC_PRIVATE | Opcodes.ACC_VOLATILE | Opcodes.ACC_SYNTHETIC;
 
-        final TypeDescription retType;
-        // getFoo
-        final String methodName;
         // getFoo$$$V
         final String handleName;
 
-        AbstractMethodImplementation(final String methodName, final TypeDescription retType) {
-            this.methodName = requireNonNull(methodName);
-            this.retType = requireNonNull(retType);
-            this.handleName = methodName + "$$$V";
+        AbstractCachedMethodImplementation(final String methodName, final TypeDescription retType) {
+            super(methodName, retType);
+            handleName = methodName + "$$$V";
         }
 
         @Override
@@ -441,7 +386,7 @@ abstract class CodecDataObjectGenerator<T extends CodecDataObject<?>> implements
         }
     }
 
-    private static final class KeyMethodImplementation extends AbstractMethodImplementation {
+    private static final class KeyMethodImplementation extends AbstractCachedMethodImplementation {
         private static final StackManipulation CODEC_KEY = invokeMethod(CodecDataObject.class,
             "codecKey", VarHandle.class);
 
@@ -451,17 +396,50 @@ abstract class CodecDataObjectGenerator<T extends CodecDataObject<?>> implements
 
         @Override
         public ByteCodeAppender appender(final Target implementationTarget) {
-            final TypeDescription instrumentedType = implementationTarget.getInstrumentedType();
             return new ByteCodeAppender.Simple(
                 // return (FooType) codecKey(getFoo$$$V);
-                THIS,
-                getField(instrumentedType, handleName),
+                loadThis(),
+                getField(implementationTarget.getInstrumentedType(), handleName),
                 CODEC_KEY,
                 TypeCasting.to(retType),
                 MethodReturn.REFERENCE);
         }
     }
 
+    private static final class NonnullMethodImplementation extends AbstractMethodImplementation {
+        private static final StackManipulation NONNULL_MEMBER = invokeMethod(CodecDataObject.class,
+                "codecMemberOrEmpty", Object.class, Class.class);
+
+        private final Class<?> bindingClass;
+        private final Method getterMethod;
+
+        NonnullMethodImplementation(final String methodName, final TypeDescription retType,
+                final Class<?> bindingClass, final Method getterMethod) {
+            super(methodName, retType);
+            this.bindingClass = requireNonNull(bindingClass);
+            this.getterMethod = requireNonNull(getterMethod);
+        }
+
+        @Override
+        public ByteCodeAppender appender(final Target implementationTarget) {
+            return new ByteCodeAppender.Simple(
+                    // return (FooType) codecMemberOrEmpty(getFoo(), FooType.class)
+                    loadThis(),
+                    loadThis(),
+                    invokeMethod(getterMethod),
+                    ClassConstant.of(TypeDefinition.Sort.describe(bindingClass).asErasure()),
+                    NONNULL_MEMBER,
+                    TypeCasting.to(retType),
+                    MethodReturn.REFERENCE);
+        }
+
+        @Override
+        public InstrumentedType prepare(final InstrumentedType instrumentedType) {
+            // No-op
+            return instrumentedType;
+        }
+    }
+
     /*
      * 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,
@@ -469,7 +447,7 @@ abstract class CodecDataObjectGenerator<T extends CodecDataObject<?>> implements
      * 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 class SimpleGetterMethodImplementation extends AbstractCachedMethodImplementation {
         private static final StackManipulation CODEC_MEMBER = invokeMethod(CodecDataObject.class,
             "codecMember", VarHandle.class, String.class);
         private static final StackManipulation BRIDGE_RESOLVE = invokeMethod(ClassGeneratorBridge.class,
@@ -481,7 +459,7 @@ abstract class CodecDataObjectGenerator<T extends CodecDataObject<?>> implements
 
         SimpleGetterMethodImplementation(final String methodName, final TypeDescription retType) {
             super(methodName, retType);
-            this.stringName = methodName + "$$$S";
+            stringName = methodName + "$$$S";
         }
 
         @Override
@@ -502,7 +480,7 @@ abstract class CodecDataObjectGenerator<T extends CodecDataObject<?>> implements
             final TypeDescription instrumentedType = implementationTarget.getInstrumentedType();
             return new ByteCodeAppender.Simple(
                 // return (FooType) codecMember(getFoo$$$V, getFoo$$$S);
-                THIS,
+                loadThis(),
                 getField(instrumentedType, handleName),
                 getField(instrumentedType, stringName),
                 CODEC_MEMBER,
@@ -511,7 +489,7 @@ abstract class CodecDataObjectGenerator<T extends CodecDataObject<?>> implements
         }
     }
 
-    private static final class StructuredGetterMethodImplementation extends AbstractMethodImplementation {
+    private static final class StructuredGetterMethodImplementation extends AbstractCachedMethodImplementation {
         private static final StackManipulation CODEC_MEMBER = invokeMethod(CodecDataObject.class,
             "codecMember", VarHandle.class, Class.class);
 
@@ -525,11 +503,10 @@ abstract class CodecDataObjectGenerator<T extends CodecDataObject<?>> implements
 
         @Override
         public ByteCodeAppender appender(final Target implementationTarget) {
-            final TypeDescription instrumentedType = implementationTarget.getInstrumentedType();
             return new ByteCodeAppender.Simple(
                 // return (FooType) codecMember(getFoo$$$V, FooType.class);
-                THIS,
-                getField(instrumentedType, handleName),
+                loadThis(),
+                getField(implementationTarget.getInstrumentedType(), handleName),
                 ClassConstant.of(TypeDefinition.Sort.describe(bindingClass).asErasure()),
                 CODEC_MEMBER,
                 TypeCasting.to(retType),
@@ -537,12 +514,12 @@ abstract class CodecDataObjectGenerator<T extends CodecDataObject<?>> implements
         }
     }
 
-    private static final class SupplierGetterMethodImplementation extends AbstractMethodImplementation {
+    private static final class SupplierGetterMethodImplementation extends AbstractCachedMethodImplementation {
         private static final StackManipulation CODEC_MEMBER = invokeMethod(CodecDataObject.class,
-            "codecMember", VarHandle.class, NodeContextSupplier.class);
+            "codecMember", VarHandle.class, CodecContextSupplier.class);
         private static final StackManipulation BRIDGE_RESOLVE = invokeMethod(ClassGeneratorBridge.class,
             "resolveNodeContextSupplier", String.class);
-        private static final Generic BB_NCS = TypeDefinition.Sort.describe(NodeContextSupplier.class);
+        private static final Generic BB_NCS = TypeDefinition.Sort.describe(CodecContextSupplier.class);
 
         // getFoo$$$C
         private final String contextName;
@@ -570,7 +547,7 @@ abstract class CodecDataObjectGenerator<T extends CodecDataObject<?>> implements
             final TypeDescription instrumentedType = implementationTarget.getInstrumentedType();
             return new ByteCodeAppender.Simple(
                 // return (FooType) codecMember(getFoo$$$V, getFoo$$$C);
-                THIS,
+                loadThis(),
                 getField(instrumentedType, handleName),
                 getField(instrumentedType, contextName),
                 CODEC_MEMBER,
@@ -578,46 +555,4 @@ abstract class CodecDataObjectGenerator<T extends CodecDataObject<?>> implements
                 MethodReturn.REFERENCE);
         }
     }
-
-    private static final class CodecHashCode implements ByteCodeAppender {
-        private static final StackManipulation THIRTY_ONE = IntegerConstant.forValue(31);
-        private static final StackManipulation LOAD_RESULT = MethodVariableAccess.INTEGER.loadFrom(1);
-        private static final StackManipulation STORE_RESULT = MethodVariableAccess.INTEGER.storeAt(1);
-        private static final StackManipulation ARRAYS_HASHCODE = invokeMethod(Arrays.class, "hashCode", byte[].class);
-        private static final StackManipulation OBJECTS_HASHCODE = invokeMethod(Objects.class, "hashCode", Object.class);
-
-        private final ImmutableMap<StackManipulation, Method> properties;
-
-        CodecHashCode(final ImmutableMap<StackManipulation, Method> properties) {
-            this.properties = requireNonNull(properties);
-        }
-
-        @Override
-        public Size apply(final MethodVisitor methodVisitor, final Context implementationContext,
-                final MethodDescription instrumentedMethod) {
-            final List<StackManipulation> manipulations = new ArrayList<>(properties.size() * 8 + 4);
-            // int result = 1;
-            manipulations.add(IntegerConstant.ONE);
-            manipulations.add(STORE_RESULT);
-
-            for (Entry<StackManipulation, Method> entry : properties.entrySet()) {
-                // result = 31 * result + java.util.(Objects,Arrays).hashCode(getFoo());
-                manipulations.add(THIRTY_ONE);
-                manipulations.add(LOAD_RESULT);
-                manipulations.add(Multiplication.INTEGER);
-                manipulations.add(THIS);
-                manipulations.add(entry.getKey());
-                manipulations.add(entry.getValue().getReturnType().isArray() ? ARRAYS_HASHCODE : OBJECTS_HASHCODE);
-                manipulations.add(Addition.INTEGER);
-                manipulations.add(STORE_RESULT);
-            }
-            // return result;
-            manipulations.add(LOAD_RESULT);
-            manipulations.add(MethodReturn.INTEGER);
-
-            StackManipulation.Size operandStackSize = new StackManipulation.Compound(manipulations)
-                    .apply(methodVisitor, implementationContext);
-            return new Size(operandStackSize.getMaximalSize(), instrumentedMethod.getStackSize() + 1);
-        }
-    }
 }