5章CPU

コンピュータシステムの理論と実装の5章のCPUの実装の部分で苦戦して、
完成するの1ヶ月ぐらいかかりました。
せっかくなんでコードを載せておこうと思います。

CHIP CPU {

    IN  inM[16],         // M value input  (M = contents of RAM[A])
        instruction[16], // Instruction for execution
        reset;           // Signals whether to re-start the current
                         // program (reset==1) or continue executing
                         // the current program (reset==0).

    OUT outM[16],        // M value output
        writeM,          // Write to M? 
        addressM[15],    // Address in data memory (of M)
        pc[15];          // address of next instruction

    PARTS:
    // Put your code here:
    Not(in=instruction[15],out=aoder);//a命令かどうか
    
    Or(a=aoder,b=instruction[5],out=Aload);//Aレジスタにloadするかどうか
    
    Mux16(a=instruction,b=outM1,sel=instruction[15],out=aregin);//A命令かC命令
    
    ARegister(in=aregin,load=Aload,out=Aout);
    
    And(a=instruction[4],b=instruction[15],out=Dload);//A命令のときDにロードしない
    DRegister(in=outM1,load=Dload,out=Dout);
    
    Mux16(a=Aout,b=inM,sel=instruction[12],out=aorm);
    
    ALU(x=Dout,y=aorm,zx=instruction[11],nx=instruction[10],zy=instruction[9],ny=instruction[8],
        f=instruction[7],no=instruction[6],out=outM1,zr=zr,ng=ng);
    
    Or16(a=outM1,b=false,out=outM);
    
    And(a=instruction[3],b=instruction[15],out=writeM);
    
    Mux(a=instruction[0],b=instruction[2],sel=ng,out=jflag1);//ジャンプ命令 マイナスかどうか
    Mux(a=jflag1,b=instruction[1],sel=zr,out=jflag2);//ジャンプ命令 0かどうか
    
    And(a=instruction[15],b=jflag2,out=jflag3);//A命令のときジャンプ命令を無視
    Not(in=jflag3,out=inc1);//pcを1進めるかどうか
    
    PC(in=Aout,load=jflag3,inc=inc1,reset=reset,out[0..14]=pc);
    
    Or16(a=Aout,b[0..15]=false,out[0..14]=addressM);
    
}

もっと効率的な方法があるかもしれませんが、とりあえず載せておきます。