;; Program selfModify.lmc ;; ;; This program uses self-modifying code to add the entries ;; in an array. The instruction labeled by addInstruction ;; is incremented each time through the loop. This has the ;; effect of changing the address of the operand to ;; reference the next entry in the array. ;; ;; Self-modifying code was a necessity in very early ;; computers. Later computers had more powerful addressing ;; modes, which are mechanisms for specifying operands. ;; Indexed addressing modes are now used for dealing with ;; arrays. ;; ;; Self-modifying code is incredibly difficult to maintain. ;; It is never used in modern software. ;; In fact, modern computers can make it impossible by ;; keeping data and instructions in different segments of ;; memory, with the instruction segment protected against ;; modification. ;; (BR loopCondition) ; Check condition first. loopBody (LDA sum) addInstruction (ADD array) (STO sum) ; Add next entry to sum. (LDA addInstruction) ; Modify the ADD instruction (ADD one) ; so that its operand part (STO addInstruction) ; references the next entry. loopIncrement (LDA i) (ADD one) (STO i) ; Increment i. loopCondition (LDA size) (SUB i) (BRZ loopDone) (BRP loopBody) ; Do loop body if size > i. loopDone (LDA sum) ;; Print out the result. (OUT) (HLT) ; Output sum and terminate. ;; Constants. one (DAT 1) size (DAT 10) ;; Variables. sum (DAT 0) i (DAT 0) array (DAT 53 27 16 64 29 51 38 42 73 7)