MSP430: codificación y conjunto de instrucciones MSP430: instruction encoding and instruction set

Apuntes de referencia · Programación en ensamblador Reference handout · Assembly programming

Tres bloques: cómo se codifica una instrucción en 16 bits, qué modo de direccionamiento elige cada combinación de bits, y la tabla completa del repertorio con su efecto sobre los flags. Three blocks: how an instruction is packed into 16 bits, which addressing mode each bit pattern selects, and the full instruction table with its effect on the status flags.

1 Codificación de instrucciones Instruction encoding

Toda instrucción del MSP430 ocupa una palabra de 16 bits. Esa palabra puede ir seguida de una o dos palabras de extensión cuando un operando necesita un dato adicional (un índice, una dirección absoluta o un inmediato). Existen tres formatos según cuántos operandos lleve la instrucción. Every MSP430 instruction occupies a single 16-bit word. That word may be followed by one or two extension words when an operand needs extra data (an index, an absolute address, or an immediate). There are three formats, depending on how many operands the instruction takes.

Opcode Rsregistro fuentesource register Rdregistro destinodestination register As / Adbits de modomode bits B/Wbyte/palabrabyte/word offset

Se usa la nomenclatura de Texas Instruments (Rs, Rd, As, Ad). En algunas hojas aparece como Rf, Rd, Df, Dd respectivamente. Texas Instruments naming is used (Rs, Rd, As, Ad). Some sheets label these Rf, Rd, Df, Dd respectively.

Formato I — Doble operandoFormat I — Double-operand  MOV · ADD · ADDC · SUB · SUBC · CMP · DADD · BIT · BIC · BIS · XOR · AND

15
14
13
12
11
10
9
8
7
6
5
4
3
2
1
0
Opcode15..12
Rs11..8
Ad7
B/W6
As5..4
Rd3..0

El opcode de 4 bits identifica la operación. Rs y As describen el origen; Rd y Ad el destino. B/W es activo a nivel bajo: 0 = palabra, 1 = byte. The 4-bit opcode names the operation. Rs and As describe the source; Rd and Ad the destination. B/W is active-low: 0 = word, 1 = byte.

OpcodeNem.OpcodeNem.OpcodeNem.
0100MOV1000SUB1100BIC
0101ADD1001CMP1101BIS
0110ADDC1010DADD1110XOR
0111SUBC1011BIT1111AND
Ejemplo de codificaciónEncoding example Codifiquemos ADD R4, R5 (ambos en modo registro, palabra): Let us encode ADD R4, R5 (both register mode, word):
Opcode=0101 · Rs(R4)=0100 · Ad=0 · B/W=0 · As=00 · Rd(R5)=0101
PalabraWord = 0101 0100 0000 0101 = 0x5405

Formato II — Un operandoFormat II — Single-operand  RRC · RRA · PUSH · SWPB · SXT · CALL · RETI

15
14
13
12
11
10
9
8
7
6
5
4
3
2
1
0
00010015..10
Opcode9..7
B/W6
As5..4
Rd3..0

Los seis bits altos son fijos (000100). El operando único usa sus propios bits de modo (As) y registro (Rd), por lo que admite todos los modos de direccionamiento. Solo RRC, RRA y PUSH tienen forma de byte; SWPB, SXT, CALL y RETI son siempre de palabra (bit 6 = 0). The top six bits are fixed (000100). The single operand carries its own mode (As) and register (Rd) bits, so it accepts every addressing mode. Only RRC, RRA and PUSH have a byte form; SWPB, SXT, CALL and RETI are word-only (bit 6 = 0).

Opcode (9..7)Opcode (9..7)Nem. ByteByte OperaciónOperation
000RRCrotación a la derecha con carryrotate right through carry
001SWPBintercambia byte alto y bajoswap high and low byte
010RRAdesplazamiento aritmético a la derechaarithmetic shift right
011SXTextiende el signo del byte bajosign-extend the low byte
100PUSHapila el operandopush the operand
101CALLllamada a subrutinacall subroutine
110RETIretorno de interrupciónreturn from interrupt
Ejemplo de codificaciónEncoding example Codifiquemos RRA R6 (modo registro, palabra): Let us encode RRA R6 (register mode, word):
000100 · Opcode(RRA)=010 · B/W=0 · As=00 · Rd(R6)=0110
PalabraWord = 0001 0001 0000 0110 = 0x1106

Formato III — Salto condicionalFormat III — Conditional jump  JMP · JEQ/JZ · JNE/JNZ · JC/JHS · JNC/JLO · JN · JGE · JL

15
14
13
12
11
10
9
8
7
6
5
4
3
2
1
0
00115..13
Cond12..10
Desplazamiento (con signo, 10 bits)Offset (signed, 10 bits)9..0

El salto es relativo al PC: PC ← PC + 2 + desplazamiento × 2. El campo de desplazamiento es de 10 bits en complemento a dos, así que vale de -512 a +511. Por el +2 de la fórmula (el PC ya apunta a la instrucción siguiente), el destino queda entre 511 palabras atrás y 512 adelante respecto al propio salto. Los tres bits de condición eligen qué flag se comprueba. The jump is PC-relative: PC ← PC + 2 + offset × 2. The 10-bit two's-complement offset field holds -512 to +511. Because of the +2 in the formula (PC already points at the next instruction), the target lands between 511 words back and 512 forward of the jump itself. The three condition bits choose which flag is tested.

CondNem. Salta si…Taken when… SentidoMeaning
000JNE / JNZZ = 0distinto / no ceronot equal / not zero
001JEQ / JZZ = 1igual / ceroequal / zero
010JNC / JLOC = 0menor sin signounsigned <
011JC / JHSC = 1mayor o igual sin signounsigned ≥
100JNN = 1negativonegative
101JGEN ⊕ V = 0mayor o igual con signosigned ≥
110JLN ⊕ V = 1menor con signosigned <
111JMPincondicionalunconditional
Cuidado con JGE y JLWatch out: JGE and JL JGE salta cuando N ⊕ V = 0 y JL cuando N ⊕ V = 1 (estándar de Texas Instruments). Algunas tablas de referencia los muestran intercambiados; estos son los valores correctos. JGE is taken when N ⊕ V = 0 and JL when N ⊕ V = 1 (Texas Instruments standard). Some reference tables show these swapped; these are the correct values.
Ejemplo de codificaciónEncoding example Codifiquemos JEQ destino con un desplazamiento de +5 palabras: Let us encode JEQ target with an offset of +5 words:
001 · Cond(JEQ)=001 · offset=00 0000 0101 (+5)
PalabraWord = 0010 0100 0000 0101 = 0x2405
DestinoTarget = PC + 2 + 5×2 = PC + 12

2 Codificación de los modos de direccionamiento Addressing-mode encoding

Los bits As (2 bits, fuente) y Ad (1 bit, destino) no eligen el modo por sí solos: su significado depende del registro al que acompañan. Esto permite reutilizar las mismas combinaciones para modos especiales mediante el generador de constantes (R2 y R3). The As (2-bit, source) and Ad (1-bit, destination) bits do not select the mode on their own: their meaning depends on the register they accompany. This lets the same combinations be reused for special modes through the constant generator (R2 and R3).

Direccionamiento de la fuente (As, 2 bits)Source addressing (As, 2 bits)
RegistroRegister AsSintaxisSyntax ModoMode Qué haceWhat it does
Rn00RnRegistroRegisterel operando es el propio registrothe operand is the register itself
Rn01X(Rn)IndexadoIndexeddirección = Rn + X (X en palabra de extensión)address = Rn + X (X in extension word)
Rn10@RnIndirectoIndirectRn contiene la dirección del operandoRn holds the operand's address
Rn11@Rn+Indirecto con postincrementoIndirect autoincrementcomo @Rn y luego Rn += 1 o 2like @Rn, then Rn += 1 or 2
R0 (PC)01ETIQSimbólico (relativo a PC)Symbolic (PC-relative)dirección = PC + Xaddress = PC + X
R0 (PC)11#NInmediatoImmediate@PC+: la constante va en la palabra de extensión@PC+: the constant is in the extension word
R2 (SR)01&ETIQAbsolutoAbsoluteX(0): dirección literal, sin sumar PCX(0): literal address, no PC added
R2 (SR)10#4ConstanteConstantgenerador de constantes: +4constant generator: +4
R2 (SR)11#8ConstanteConstantgenerador de constantes: +8constant generator: +8
R3 (CG2)00#0ConstanteConstantgenerador de constantes: 0constant generator: 0
R3 (CG2)01#1ConstanteConstantgenerador de constantes: +1constant generator: +1
R3 (CG2)10#2ConstanteConstantgenerador de constantes: +2constant generator: +2
R3 (CG2)11#-1ConstanteConstantgenerador de constantes: 0xFFFFconstant generator: 0xFFFF
Direccionamiento del destino (Ad, 1 bit)Destination addressing (Ad, 1 bit)
RegistroRegister AdSintaxisSyntax ModoMode Qué haceWhat it does
Rn0RnRegistroRegisterel destino es el propio registrothe destination is the register itself
Rn1X(Rn)IndexadoIndexeddirección = Rn + Xaddress = Rn + X
R0 (PC)1ETIQSimbólico (relativo a PC)Symbolic (PC-relative)dirección = PC + Xaddress = PC + X
R2 (SR)1&ETIQAbsolutoAbsoluteX(0): dirección literalX(0): literal address
El generador de constantesThe constant generator R2 (SR) y R3 (CG2) no solo son registros: ciertas combinaciones de sus bits de modo fabrican las constantes más usadas (0, 1, 2, 4, 8 y −1) sin gastar una palabra de extensión ni un ciclo de lectura. Por eso el destino solo necesita 1 bit (Ad): los modos indirecto e inmediato del destino se obtienen, cuando hacen falta, escribiendo 0(Rn). R2 (SR) and R3 (CG2) are not only registers: certain combinations of their mode bits manufacture the most common constants (0, 1, 2, 4, 8 and −1) without spending an extension word or a read cycle. That is why the destination needs only 1 bit (Ad): indirect and immediate destinations are obtained, when needed, by writing 0(Rn).

3 Conjunto de instrucciones Instruction set

El núcleo del MSP430 tiene 27 instrucciones reales. El resto son emuladas: el ensamblador las traduce a una instrucción real, sin coste extra. [.T] indica que existe forma de byte (.B) y palabra (.W). The MSP430 core has 27 real instructions. The rest are emulated: the assembler rewrites them into a real instruction at no extra cost. [.T] marks that a byte (.B) and word (.W) form exist.

f = origen (fuente), admite todos los modos.src = source, any mode. d = destino (solo Rn o M(Rn)).dst = destination (Rn or M(Rn) only). EMU= emulada (muestra la instrucción real).= emulated (shows the real instruction).

Flags:Flags: * según resultadoset by result sin cambiounchanged 0/1 forzadoforced Z a 1 si resultado ≠ 0set if result ≠ 0

Por qué existen las instrucciones emuladasWhy emulated instructions exist El opcode de doble operando son solo 4 bits (12 huecos), y están los 12 ocupados: no queda patrón libre para un INC o un CLR nativos. En lugar de inventar opcodes que no caben, el ensamblador los reescribe sobre las instrucciones reales. El generador de constantes (R2 y R3 fabrican 0, 1, 2, 4, 8 y −1 sin palabra de extensión ni ciclo extra) hace que la traducción sea gratis: INC dADD #1, d pesa y tarda lo mismo que un INC nativo. RET, NOP, POP o BR no usan constantes: aprovechan que PC y SP son registros normales. Como la emulada es la instrucción real por debajo, sus flags son los de esa instrucción (por eso INV = XOR #-1 toca flags, y CLR = MOV #0 no). The double-operand opcode is only 4 bits (12 slots), and all 12 are taken: there is no free pattern left for a native INC or CLR. Rather than inventing opcodes that do not fit, the assembler rewrites them onto the real instructions. The constant generator (R2 and R3 produce 0, 1, 2, 4, 8 and −1 with no extension word or extra cycle) makes the rewrite free: INC dstADD #1, dst is the same size and speed as a native INC would be. RET, NOP, POP and BR use no constants: they exploit that PC and SP are ordinary registers. Because an emulated instruction is the real one underneath, its flags are that instruction's flags (which is why INV = XOR #-1 touches flags, while CLR = MOV #0 does not).
Nem. Op.Op. Función / EmulaciónFunction / Emulation V N Z C
MovimientoMove
MOV[.T]f, dsrc, dstd ← fdst ← src{----}
PUSH[.T]fsrcSP ← SP-2, MEM(SP) ← fSP ← SP-2, MEM(SP) ← src{----}
POP[.T] EMUddstd ← MEM(SP), SP ← SP+2  ≡ MOV @SP+, ddst ← MEM(SP), SP ← SP+2  ≡ MOV @SP+, dst{----}
SWPBfsrcf15..8 ↔ f7..0src15..8 ↔ src7..0{----}
CLR[.T] EMUddstd ← 0  ≡ MOV #0, ddst ← 0  ≡ MOV #0, dst{----}
AritméticasArithmetic
ADD[.T]f, dsrc, dstd ← d + fdst ← dst + src{FFFF}
ADDC[.T]f, dsrc, dstd ← d + f + Cdst ← dst + src + C{FFFF}
ADC[.T] EMUddstd ← d + C  ≡ ADDC #0, ddst ← dst + C  ≡ ADDC #0, dst{FFFF}
INC[.T] EMUddstd ← d + 1  ≡ ADD #1, ddst ← dst + 1  ≡ ADD #1, dst{FFFF}
INCD[.T] EMUddstd ← d + 2  ≡ ADD #2, ddst ← dst + 2  ≡ ADD #2, dst{FFFF}
SUB[.T]f, dsrc, dstd ← d − fdst ← dst − src{FFFF}
SUBC[.T]f, dsrc, dstd ← d − f − Cdst ← dst − src − C{FFFF}
SBC[.T] EMUddstd ← d − C  ≡ SUBC #0, ddst ← dst − C  ≡ SUBC #0, dst{FFFF}
DEC[.T] EMUddstd ← d − 1  ≡ SUB #1, ddst ← dst − 1  ≡ SUB #1, dst{FFFF}
DECD[.T] EMUddstd ← d − 2  ≡ SUB #2, ddst ← dst − 2  ≡ SUB #2, dst{FFFF}
CMP[.T]f, dsrc, dstd − f  (solo flags)dst − src  (flags only){FFFF}
TST[.T] EMUddstd − 0  ≡ CMP #0, ddst − 0  ≡ CMP #0, dst{0FF1}
SXTfsrcf15..8 ← f7src15..8 ← src7{0FFZ}
INV[.T] EMUddstd ← NOT d  ≡ XOR #-1, ddst ← NOT dst  ≡ XOR #-1, dst{FFFZ}
DADD[.T]f, dsrc, dstd ← d + f + C  (BCD)dst ← dst + src + C  (BCD){FFFF}
DADC[.T] EMUddstd ← d + C  (BCD) ≡ DADD #0, ddst ← dst + C  (BCD) ≡ DADD #0, dst{FFFF}
Lógicas y manejo de bitsLogic and bit handling
AND[.T]f, dsrc, dstd ← d AND fdst ← dst AND src{0FFZ}
BIT[.T]f, dsrc, dstd AND f  (solo flags)dst AND src  (flags only){0FFZ}
BIC[.T]f, dsrc, dstd ← d AND NOT fdst ← dst AND NOT src{----}
BIS[.T]f, dsrc, dstd ← d OR fdst ← dst OR src{----}
XOR[.T]f, dsrc, dstd ← d XOR fdst ← dst XOR src{FFFZ}
Bits de estadoStatus bits
CLRC EMUC ← 0  ≡ BIC #1, SR{---0}
SETC EMUC ← 1  ≡ BIS #1, SR{---1}
CLRN EMUN ← 0  ≡ BIC #4, SR{-0--}
SETN EMUN ← 1  ≡ BIS #4, SR{-1--}
CLRZ EMUZ ← 0  ≡ BIC #2, SR{--0-}
SETZ EMUZ ← 1  ≡ BIS #2, SR{--1-}
Desplazamiento y rotaciónShift and rotate
RRC[.T]fsrcrotación a la derecha con carryrotate right through carry{0FFF}
RLC[.T] EMUddstrotación a la izquierda con carry  ≡ ADDC d, drotate left through carry  ≡ ADDC dst, dst{FFFF}
RRA[.T]fsrcdesplazamiento aritmético a la derechaarithmetic shift right{0FFF}
RLA[.T] EMUddstdesplazamiento aritmético a la izquierda  ≡ ADD d, darithmetic shift left  ≡ ADD dst, dst{FFFF}
Salto y subrutinasJump and subroutines
JMPdspPC ← PC + dsp×2  (incondicional)(unconditional){----}
JEQ / JZdspsalta si Z = 1jump if Z = 1{----}
JNE / JNZdspsalta si Z = 0jump if Z = 0{----}
JC / JHSdspsalta si C = 1 (≥ sin signo)jump if C = 1 (unsigned ≥){----}
JNC / JLOdspsalta si C = 0 (< sin signo)jump if C = 0 (unsigned <){----}
JNdspsalta si N = 1jump if N = 1{----}
JGEdspsalta si N ⊕ V = 0 (≥ con signo)jump if N ⊕ V = 0 (signed ≥){----}
JLdspsalta si N ⊕ V = 1 (< con signo)jump if N ⊕ V = 1 (signed <){----}
BR EMUfsrcPC ← f  ≡ MOV f, PCPC ← src  ≡ MOV src, PC{----}
CALLfsrcSP ← SP-2, MEM(SP) ← PC, PC ← fSP ← SP-2, MEM(SP) ← PC, PC ← src{----}
RET EMUPC ← M(SP), SP ← SP+2  ≡ MOV @SP+, PC{----}
RETISR ← M(SP), SP ← SP+2, PC ← M(SP), SP ← SP+2{FFFF}
MisceláneaMiscellaneous
DINT EMUGIE ← 0  ≡ BIC #8, SR{----}
EINT EMUGIE ← 1  ≡ BIS #8, SR{----}
NOP EMUno hace nadano operation  ≡ MOV R3, R3{----}

4 Ciclos de reloj y longitud Clock cycles and length

El coste en ciclos (MCLK) depende solo de los modos de direccionamiento, no de la operación: la ALU no añade ciclos. Cada acceso a memoria cuesta un ciclo, y el byte y la palabra tardan lo mismo. Una instrucción EMU tarda exactamente lo que su instrucción real. Valores del MSP430 en modo CPU de 16 bits (64 KB). Cycle cost (MCLK) depends only on the addressing modes, not on the operation: the ALU adds no cycles. Each memory access costs one cycle, and byte and word take the same time. An EMU instruction takes exactly what its real instruction takes. Values for the MSP430 in 16-bit (CPU) mode (64 KB).

Formato I · doble operando (MOV, ADD, CMP, …)Format I · double operand (MOV, ADD, CMP, …)
OrigenSource Destino: registro (Rn)Destination: register (Rn) Destino en memoria (indexado / simbólico / absoluto)Destination in memory (indexed / symbolic / absolute)
cicloscycles pal.words cicloscycles pal.words
Rn registroregister1142
@Rn indirectoindirect2152
@Rn+ postincrementoautoincrement2152
#N inmediatoimmediate2253
X(Rn) indexadoindexed3263
ETIQ simbólicosymbolic3263
&ETIQ absolutoabsolute3263

El destino solo admite 4 modos: registro y tres en memoria (indexado X(Rn), simbólico ETIQ y absoluto &ETIQ), que cuestan lo mismo y por eso comparten columna. No hay destino indirecto, postincremento ni inmediato. The destination supports only 4 modes: register and three in memory (indexed X(Rn), symbolic ETIQ and absolute &ETIQ), which cost the same and therefore share a column. There is no indirect, autoincrement or immediate destination.

+1 si el destino es el PC (p. ej. BR, MOV x, PC).if the destination is the PC (e.g. BR, MOV x, PC). +1 en DADD.for DADD.

El coste lo fijan los bits As/Ad: los modos inmediato (#N), simbólico (ETIQ) y absoluto (&ETIQ) reutilizan la codificación —y el tiempo— de @Rn+ (As=11) y X(Rn) (As=01). Por eso una tabla indexada por bits necesita menos filas (ver Sección 2). Cost is set by the As/Ad bits: the immediate (#N), symbolic (ETIQ) and absolute (&ETIQ) modes reuse the encoding —and the timing— of @Rn+ (As=11) and X(Rn) (As=01). That is why a bit-indexed table needs fewer rows (see Section 2).

Formato II · un operandoFormat II · single operand
Modo del operandoOperand mode RRA · RRC · SWPB · SXT PUSH CALL pal.words
Rn1341
@Rn3441
@Rn+3451
#N452
X(Rn)4552
ETIQ4552
&ETIQ4552

PUSH y CALL solo leen el operando: aceptan cualquier modo, incluido inmediato (PUSH #5, CALL #rutina) e indexado. RRA/RRC/SWPB/SXT modifican el operando en su sitio, así que admiten todos los modos menos inmediato (no se puede reescribir una constante): de ahí el «—». PUSH and CALL only read the operand: any mode is allowed, including immediate (PUSH #5, CALL #routine) and indexed. RRA/RRC/SWPB/SXT modify the operand in place, so they allow every mode except immediate (you cannot rewrite a constant): hence the “—”.

Formato III (saltos) y operaciones especialesFormat III (jumps) and special operations
OperaciónOperation CiclosCycles pal.words
Jxx salto cond. / incond.cond. / uncond. jump21
RET ≡ MOV @SP+, PC31
RETI51
Atención a interrupciónInterrupt service6
Reset4
Modo CPU de 16 bits16-bit (CPU) mode Usamos el MSP430 en modo CPU de 16 bits (los 64 KB bajos). El FR6989 tiene además el núcleo CPUXV2 con direccionamiento de 20 bits e instrucciones extendidas (MOVA, CALLA, .A), que aquí no se usan. We use the MSP430 in 16-bit (CPU) mode (the lower 64 KB). The FR6989 also has the CPUXV2 core with 20-bit addressing and extended instructions (MOVA, CALLA, .A), not used here.
EjemploExample MOV.W 4(R5), &2000horigen indexado X(Rn) → destino absoluto en memoria.indexed source X(Rn) → absolute destination in memory.
Formato I, fila X(Rn) → memoria:Format I, row X(Rn) → memory: 6 cicloscycles · 3 palabraswords