[llvm-dev] Lowering For Loops to use architecture "loop" instruction

Tim Northover via llvm-dev llvm-dev at lists.llvm.org
Wed Jun 1 20:43:25 PDT 2016

On 1 June 2016 at 20:18, Dilan Manatunga via llvm-dev
<llvm-dev at lists.llvm.org> wrote:
> I'm working on project which involves writing a backend for a hypothetical
> architecture. I am currently trying to figure out the best way to translate
> for loops to use a specialized "loop" instruction the architecture supports.
> The instruction is similar X86's loop instruction, where a register is
> automatically decremented and the condition is automatically checked to see
> if loop execution should continue.

This sounds like it's not something the TableGen patterns could
handle, but ought to be fairly easy during ISelDAGToDAG. You'd be
looking for a something like "(br_cc SETGT, (sub $iter, 1), 0,
$GoAgain)". The C++ code is needed because your final LOOP instruction
also has an output (induction variable for the next iteration) that
needs to be propagated from the "(sub $iter, 1)".

Some very vague and untested pseudo-code would be:

    // To produce a (LOOP Chain, InductionVariable, Dest)
    SDNode *SelectLOOPFromBR_CC(SDNode *N) {
      // TODO: check whatever conditions (sub 1, SETGT, ..).
      SDValue IV = N->getOperand(1);
      SDNode *LOOP = CurDAG->getMachineNode(XYZ::LOOP, DL,
              CurDAG->getVTList(MVT::Other, IV.getType()),
IV.getOperand(0), N->getOperand(3));
      CurDAG->ReplaceAllUsesWith(IV, SDValue(Loop, 1));
      return LOOP;

where the key point is that you have to manually call
ReplaceAllUsesWith to move your induction variable onto the LOOP
instruction. The rest is just bog-standard "match a BR_CC" code.

The LOOP instruction would output a GPR (new induction variable) and
take the old one as an input (tied via "let Constraints = ..." if
they're really the same register), as well as a destination basic

Hope this is a little helpful.


P.S. Beware the position of the Chain changes between
pre-isel/post-isel and I can never remember which way round it should
be. There's at least a 50% chance I've got it wrong here. Probably
closer to 75%.

More information about the llvm-dev mailing list