Runtime generics cleanup

Reorganize generics so the runtime and the generated code avoids unchecked casts.