javadivmod

Does java have a divmod instruction?


Besides divmod being a native instruction on many chipsets, it also is a lot easier on the eyes when subdividing a number in multiple different denominations

(which happens with e.g. milliseconds -> datetime conversion, or cents -> coin denomination conversion).

So is there a divmod that returns both the result of the division and of the remainder at the same time?


Solution

  • The HotSpot JIT compiler will replace division and modulo operations against the same arguments with a single divmod operation, if supported. So while this may not address the readability concerns, you don't need to worry about performance.

    From the OpenJDK 9 source code:

    case Op_ModI:
      if (UseDivMod) {
        // Check if a%b and a/b both exist
        Node* d = n->find_similar(Op_DivI);
        if (d) {
          // Replace them with a fused divmod if supported
          if (Matcher::has_match_rule(Op_DivModI)) {
            DivModINode* divmod = DivModINode::make(n);
            d->subsume_by(divmod->div_proj(), this);
            n->subsume_by(divmod->mod_proj(), this);
          } else {
            // replace a%b with a-((a/b)*b)
            Node* mult = new MulINode(d, d->in(2));
            Node* sub  = new SubINode(d->in(1), mult);
            n->subsume_by(sub, this);
          }
        }
      }
      break;
    

    By using diagnostic options to print the generated JIT instructions, I was able to see that a method that used both idiv and irem instructions at the C1 optimization level used only a single idiv instruction at the C2 level.