Skip to content

In Which I Move Closer to the Robot Apocalypse – LLVM For the 1802 Gets Conditional Branches

April 2, 2015

Well, closer to being Turing complete anyway. With the help of Pierre Andre Saulais of Codeplay I have got simple conditional branches into LLVM for the 1802. I also got a huge “leg” up on understanding how LLVM instruction selection works.

The code below is pretty awful but baby steps will still get us to the dawn of SkyNet – it will just take time.

int foo(int i){
  while(i>0){
    asm("SEQ");
    asm("REQ");
    i--;
  }
  return 0;
}
foo:
	LD2I r1,#1
	wblt r0,r1,.LBB0_2
	LBR .LBB0_1
.LBB0_1:
	SEQ
	REQ
	LD2I r1,#65535
	add r0, r0, r1
	LD2I r1,#0
	bgt r0, r1, .LBB0_1
	LBR .LBB0_2
.LBB0_2:
	LD2I r0,#0
	SEP 5

In the end it came down to putting a few lines into LEGInstrInfo.td and one C++ routine to pretty print the branch condition:

def : Pat<(brcc SETGT, i32:$src1, i32:$src2, bb:$dst), (BCmp 18, $src1, $src2, $dst)>;
def : Pat<(brcc SETLT, i32:$src1, i32:$src2, bb:$dst), (BCmp 20, $src1, $src2, $dst)>;
def cc_val : Operand<i32>{
  let PrintMethod = "printCondCode";
}
let isTerminator = 1, isBranch = 1 in {
  def BCmp : InstLEG<(outs), (ins cc_val:$cc, GRRegs:$src1, GRRegs:$src2, b_target:$dst),
                     "b$cc $src1, $src2, $dst",  []> {
  }
}

The patterns like (brcc SETGT, i32:$src1, i32:$src2, bb:$dst) match the LLVM intermediate language conditional branch. SETGT is the condition to branch on – these evaluate to numerics so the let PrintMethod=”printCondCode” invokes a bit of C code that makes them readable.

The big learning was around how LLVM actually selects instructions. The routine
SDNode *LEGDAGToDAGISel::Select(SDNode *N)
in lib/Target/LEG/LEGISelDAGToDAG.cpp gets called for each llvm ir statement. It can elect to generate code itself and return it or it can default to returning SelectCode(N). SelectCode is what scans the patterns from InstrInfo.td. If It fails to find a match you get a gloriously hex-y failure message.

I could not have done this without direct help from Pierre Andre but I do feel a bit smarter today.

Advertisements

From → LLVM

Leave a Comment

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: