Showing posts with label Microprocessors and Microcontrollers. Show all posts
Showing posts with label Microprocessors and Microcontrollers. Show all posts

Tuesday, 13 November 2012

Orthogonal instruction set


Definition:
"In computer engineering, an orthogonal instruction set is an instruction set architecture where all instruction types can use all addressing modes. It is 'orthogonal' in the sense that the instruction type and the addressing mode vary independently."

The story of orthogonal instruction set:
In the past, because the memory is very precious, so the processor designer tends to make instructions as powerful as possible. So they hope one instruction can perform full function like get data from memory and then perform the calculation. They make all instructions can have all the addressing modes. By this way, one instruction can fetch data and do the calculation at the same time. 

But this will inscrease the complexity of the processor design. Also, accessing memory directly is very time-consuming, so some companies choose to use RISC processor (like ARM) which has a LOAD-STORE arhitecture to reduce the complexity of the design.

Examples: the DEC PDP-11 and Motorola 68000 are nearly orthogonal instruction sets, and VAX is an example of CPU with fully orthogonal instruction set.


References:

Monday, 20 August 2012

Short introduction of Scalar processor and Vector processor


Introduction:

Scalar processors are those what we talking about usually, like ARM, MSP430, Atemel ... 
They operate data with one unit, although now some processor can operate multiple data at the same time with multi-core. But it is still called Scalar processor.

Vector processor can operate data with vector as unit, which means it can work like MATLAB to calculate vector arithmetics directly, unlike the normal calculators have to go through a lot of steps to get the results of vector arithmetics.

So vector processor is a very good tool which can be used in graphic applications, such as high-resolution device, video game ... Actually, in 2000, IBM, Toshiba and Sony collaborated to create the Cell processor, consisting of one scalar processor and eight vector processors, which found use in the Sony PlayStation 3 among other applications.


But for the detail on the hardware implementation in Vector processors, and how are they different from the scalar processors? This will be the future topic, depends on my shcedule.

References:

Sunday, 19 February 2012

Full stack and empty stack


Full stack and empty stack
Full stack:
A full stack is where the stack pointer points to the last data item written
Empty stack:
Empty stack is where the stack pointer points to the first free slot.

How to manage a stack:

Only 56 instructions in ARM Cortex-M0


16-Bit Thumb Instructions Supported on the Cortex-M0 Processor

ADC      ADD        ADR     AND     ASR     B           BIC        BLX          BKPT     BX
CMN     CMP        CPS      EOR     LDM     LDR     LDRH     LDRSH     LDRB     LDRSB
LSL        LSR         MOV    MVN    MUL    NOP     ORR       POP          PUSH     REV
REV16   REVSH    ROR     RSB      SBC     SEV      STM       STR          STRH      STRB
SUB       SVC         SXTB   SXTH   TST      UXTB   UXTH    WFE         WFI         YIELD


32-Bit Thumb Instructions Supported on the Cortex-M0 Processor

BL     DSB     DMB     ISB     MRS     MSR

The instructions in the Cortex-M0 processor can be divided into various groups based on functionality:
  • Moving data within the processor (MOV  MRS  MSR)
  • Memory accesses (LDR  LDRH  LDRB  LDRSH  LDRSB  STR  STRH  STRB  LDM  STM)
  • Stack memory accesses (PUSH  POP)
  • Arithmetic operations (ADD  ADR  SUB  ADC  SBC  RSB  MUL  CMP  CMN)
  • Logic operations (AND  ORR  EOR  BIC  MVN  TST)
  • Shift and rotate operations (ASR  LSL  LSR  ROR )
  • Extend and reverse ordering operations (REV  REV16  REVSH  SXTB  SXTH  UXTB  UXTH)
  • Program flow control (branch, conditional branch, and function calls) (B  BL  BX  BLX)
  • Memory barrier instructions (DMB  DSB  ISB)
  • Exception-related instructions (SVC  CPS)
  • Sleep mode feature-related instructions (WFI  WFE  SEV)
  • Other functions (NOP  BKPT  YIELD)

Friday, 17 February 2012

Status flags


Status flags in ARM processor

The most common status flags are: V (overflow), N (sign status), Z (zero or not), C (carry bit, remember it is not borrow bit of substraction).
  • V - This flag is set when the sign of result is wrong. This methodology is called "twos complement"
    • For addition, V is set if msb (s) is equal to msb (d) and msb (result) is not equal to msb (d), which means the addition two positive numbers is negative, or the addition of two negative numbers is positive.
    • For substraction, V is set if msb (s) is not equal to msb (d) and msb (result) is not equal to msb (d), which means the result of one positive number substracting negative number is negative, or the result of one negative number substracting positive number is positive.
    • Anyway, because the most significant bit represents the sign bit, so when we do some operation with large number which will make the result exceed the scope of operand. V represents the wrong operation. 
    • Because assembly number cannot recognize signed or unsigned, so with the help of V bit we can control the calculation is signed or unsigned.
  • N - It is set is msb of the result is 1 which means the result can be treated as negative number.
  • Z - It is set if the result is zero.
  • C - It is set if the result of addition exceed the destination register and is cleared if a substraction generates a borrow bit. We will talk about this in the next part for detail.


Carry flag vs. Borrow flag[1]

"While the carry flag is well-defined for addition, there are two possible ways to use the carry flag for subtractive operations.
One uses the bit as a borrow flag, setting it if a<b when computing a−b, and a borrow must be performed. A subtract with borrow (SBB) instruction will compute a−b−C = a−(b+C), while a subtract without borrow (SUB) acts as if the borrow bit were clear. The 8080, Z80, x86 and 68k families (among others) use a borrow bit.[1]
The other takes advantage of the identity that −x = not(x)+1 and computes a−b as a+not(b)+1. The carry flag is set according to this addition, and subtract with carry computes a+not(b)+C, while subtract without carry acts as if the carry bit were set. The 6502 and PowerPC processors use this convention. The 6502 is a particularly well-known example because it does not have a subtract without carry operation, so software must ensure that the carry flag is set before every subtract operation where a borrow is not required.

The modern convention is to refer to the first alternative as a "borrow bit", while the second is called a "carry bit". However, there are exceptions in both directions; the VAX and NS320xx architectures use the borrow bit convention, but call their a−b−C operation "subtract with carry" (SBWC). PA-RISC uses a carry bit convention, but calls its a+not(b)+C operation "subtract with borrow" (SUBB)."


There are two types of substract with carry bit: a-b-C type and a+not(b)+C.

a-b-C type:
When borrow, it is set as 1. When no borrow, set 0.
a+not(b)+C type:
When borrow, it is set as 0. When no borrow, set 1. In fact, this type of substraction calculation is exactly addition calculation. Here must remember "not(b)+1" is the complement of "b".


References:

Saturday, 28 January 2012

ARM memory management (Chip S3C2440 with Core ARM920T)


  1. 128MB for every bank.
  2. Total 8 memory banks.Six memory banks for ROM, SRAM, etc.Remaining two memory banks for ROM, SRAM, SDRAM, etc .
  3. There are 7 banks with fixed start address.
  4. The size and start address of bank7 can change, while the size of bank6 is changeable (equal to the size of bank7), but with fixed start address.

The memory mapping is shown below:

From picture above, we can see:
  1. Although S3C2440 is a 32-bit chip which theoretically means the chip can have a maximum memroy 4GB, but in fact it only has 1GB memory to use for data and code. As for the remaining 3GB, some of which is used for special registers, and the others is not used (it is kind of waste, isn't it!).
  2. The start address and size of bank7 is changeable, but the sizes of bank6 and bank7 have to keep the same. So the size of bank6 is also changeable, but with fixed start address.
  3. Usually, the bank6 and bank7 are used for SDRAM, so basically bank6 and bank7 is used for RAM. So the maximun of RAM of S3C2440 chip is 256MB.

Memory organization with S3C2440 application:

I will talk about memory organization according to board TQ2440 which is bought from China. The specification of core board is:
  • S3C2440 CPU
  • 64MB SDRAM
  • 2MB Nor flash
  • 512MB Nand flash
There are three kinds of memory chip can be used with S3C2440: SDRAM, Nor flash and Nand flash. We can choose Nor flash or Nand flash as the working ROM though pins OM1 and OM2 like the table below.


S3C2440 chip uses address pins LADDR0-LADDR26 (128MB) and banks selection pins nGCS0-nGCS7 to locate the certain memory units. So when the chips try to decode the PC register, there are two decoding modes:
ROM: nGCS pin + address pins
RAM: nGCS pin + address pins (Multplexing)

SDRAM connections:

Here we talk about SDRAM first, which uses multiplexing addressing mode to access memory units. Two 32MB 16-bit width SDRAM chips is used together to form 64MB RAM which has 32-bit data width. 


From the schematic above, we can see:
  1. The address pins are multiplexing pins: A0-A12 for rows, A0-A8 for columns.
  2. BA0-BA1 are used for selecting the internal banks of SDRAM.
  3. The memory system is 4-byte alignment. So the address pins are used from LADDR2, LADDR0 and LADDR1 are not used.
  4. nSCS is the chip selection pin connected with nGCS6 pin of S3C2440, which means SDRAM working in address space 0x30000000.
Here we can calculate how we get the 64MB RAM like below:
2^(13(A0-A12)+9(A0-A8)+2(BA0,BA1))*16 bit*2 chip = 64MB

Nor flash connections:

Nor flash is an XIP (executed in place) memory. It uses linear addressing mode which make the addressing is the easiest.

From the schematic above, we can see:
  1. There are 20 address pins (A20 and A21 are not used).
  2. The data width is 16-bit, so the address pins are used from LADDR1. Does this mean we have to only store the THUMB instructions which are 16-bit size in this kind of Nor flash?
  3. Here the chip selection pin is connected to the pin nGCS0 of S3C2440 chip, which means it will work in address space 0x00000000.
The 2MB size of Nor flash can be calculated like below:
2^20(A0-A19)*16bit = 2MB

Internal SRAM:

S3C2440 chip has its own internal SRAM whose size is 4KB. This is far enough from storing the kernel of operating system and it is volatile. So we have to use externel memories.
When we use Nand flash mode (OM(1,0) = 00), the 4KB SRAM is mapped to address 0x00000000, now it is called "Steppingstone", so that it can load the boot program.
When using Nor flash mode (OM(1,0) = 10 or 01), the SRAM mapping is changed into address 0x40000000, because Nor flash is mapped to 0x00000000 to boot program in Nor flash.

Anyway, when the system resets, the program is always executed from address 0x00000000.

Summary:

The memory location of board TQ2440 is:

0x00000000->0x001FFFFF                                                         2M Nor flash
0x30000000->0x33FFFFFF                                                         64M SDRAM
0x00000000->0x00001000 or 0x40000000->0x40001000          4K Internal SRAM
0x48000000~                                                                                Special registers

As for Nand flash, which can be regarded as the normal peripherals whithout mapping in address space of S3C2440. So here Steppingstone is coming. When the system resets, the first 4KB in Nand flash is carried into the Steppingstone by Nand flash controller. The 4KB bootloader program loads the kernel of operating system into the SDRAM which is mapped to 0x30000000.
We can see the design of Steppingstone in S3C2440 is sweet. Without Steppingstone, we have to use an extra Nor flash to store the bootloader code which can load the kernel image of operating system. Now with Steppingstone, we can save both bootloader code and kernel image in Nand flash.

References:
[1] S3C2440 datasheet, Sumsung
[2] S3C2440存储控制器和MMU浅析, http://blog.csdn.net/ayangke/article/details/6880846
[3] TQ2440学习笔记-裸奔程序流水灯, http://www.dpj365.com/blog/?tag=%E7%AC%94%E8%AE%B0


Sunday, 11 December 2011

Entering different modes in ARM architecture

In ARM srchitecture, there are several processor modes provided for safty issues. Except user mode, other six modes are called "priviledge mode". And except user mode and system mode, other fives are also called  "exception mode"[8]. This is shown in Table 3-1.
                                   
User mode: Application usually runs in the user mode (except system mode since ARMv4). In user mode, the memory access is restricted. For example, you are not allowed to access the memory where OS kernel  is stored[7]. And you also cannot write CPSR register. Hardware devices cannot be read directly in user mode.
So here when you start up the system(i.e. 2440init.S) as surpervisor mode and go to user mode, you can only enter other modes by exceptions because we cannot change the content of CPSR in user mode(see figure 2-6). For example, you can use SWI to enter supervisor mode. An interrupt signal exception change mode into IRQ or FIQ.
Supervisor mode(SVC mode): It is mainly used by SWIs and the OS [3]. In this mode, you can access all the resources of system such as memory, CPSR, hardware devices and so on. So in OS, usually system call is executed in SVC mode[4], so you have to use SWI to enter system call.


System mode: It debuts since ARMv4. It is simlilar to user mode except it can access all the resources, so it is used to develop nonOS program. You can enter any mode in system mode by instructions MRS and MSR directly.


Summary: There are two ways to change the processor modes: use instructions MRS and MSR(excluding User mode) or through exceptions. And the usual procedure of ARM program execution is shown in below.

Reference: 
[1] ARM official document, "Using the arm assembler", P12(total)
[2] Registers and processor modes,  http://www.heyrick.co.uk/assembler/regs.html
[3] http://stackoverflow.com/questions/478929/user-mode-vs-supervisor-mode
[4] http://en.wikipedia.org/wiki/System_call#Processor_mode_and_context_switching
[5] 第三篇 ARM7的模式, http://hi.baidu.com/ch314156/blog/item/ad59333aac346bee828b13ff.html
[6] http://zhidao.baidu.com/question/238424160.html
[7] http://topic.csdn.net/u/20091222/15/31840752-81bc-4520-88c2-2f740ecd046e.html
[8] http://zhidao.baidu.com/question/24036020.html?fr=qrl&cid=89&index=1&fr2=query


Thursday, 8 December 2011

Difference between instructions, pseudo-instructions and assembly directives

Instruction: 
No need to say more. It is a kind of mnemonic which can be mapped into binary code directly by translating opcode and operand.

Pseudo-instruction: 
Pseudo-instruction is not a real instruction related to ISA(Instruction Set Architecture). It exists in assembler which can produce corresponding real instructions after assembling. For example, LDR R0, = immediate is a pseudo-instruction. It may produce one MOV or several instructions which depends on the size of the immediate.
PS: LDR R0, [indirect address] is not a pseudo-instruction. It is a real instruction in ISA of ARM.
Pseudo instructions are essentially pre-defined macros, so you can implement your own pseudo instructions if you want.

Directive: 
Also not a real instruction, and only exists in assembler. But after assembling, it does not produce any code. It just indicates the assembler how to configure the processor, for example: changing modes(ARM or Thumb-2), code location (AREA NAME, CODE(DATA), READONLY(READWRITE))
So in 8051, DB, DS, EQU, DSEG, CSEG and others similar are all direcitives

Reference:http://www.embeddedrelated.com/usenet/embedded/show/25889-1.php, accessed on Dec 8th, 2011

Thursday, 17 November 2011

关于2440init.s之一(转载)


2440的初始化程序,也可以说是bootloader中的精华部分,承载着程序执行的第一条指令
的重要任务,所有得程序要想执行,那么首先必须过Init.s这一关啊。

那么Init究竟做了些什么呢,咳,这的确是一个头大的问题,起初真的是一头雾水啊

首先,定义了入口地址,一般处理器上电以后,都会从存储器的0地址开始执行,好了,现
在就有第一个问题出现了,这个存储器的0地址是个什么概念;

要解决这个问题,首先必须弄清楚你的系统有哪些存储器。一般来说,不外乎rom和ram,
还有flash,flash是很重要的,因为我们的程序就放在那儿。可是我们知道,flash的物理
地址一般不会是从0开始啊,呵呵,的确是这么回事,那这个0到底是什么呢,很简单,偏
移量啊,就是flash的base+xx,这个xx就是0,^_^,就这么简单

接下来,出现第二个问题,程序从0地址执行,那么下一个要执行的代码是什么呢,他是通
过什么跳转到第二个代码呢?

这个问题的回答要针对具体的处理器了,一般代码的存放都是连续存放的,就是第一个地
址,第二个地址,代码占多大空间,那么第二个地址就是第一个地址+第一条指令占居的
空间
比如说我们现在使用的2440,它是32位宽的,就是说每条指令译码后,为一个32位的二进
制数,它的不同的位分别代表了这个指令要做什么。那么这样一条代码在存储器中就要占
据32位。那我们知道现在一般存储器都是按字节存放的,如此算来,一条指令要占据4个字
节,事实上也确实如此。

由此我们得知,假如说我们的第一条指令存放在0x00000000处,那么第二条指令就应该存
放在0x00000004处了。^_^一点都不假。并且,这里还要说明一点,由于它每条指令都是4
字节,也即一个字的宽度,同时arm在寻址的时候,是字对齐的,所以,arm的地址位的低
两位(如A1,A0)在到存储器中寻找的时候,是没有效的,因为存储器按字节存取,而一
条指令占4个字节,所以呢,处理器每次都是4个字节的拿或放,因而2^2=4,所以A1和A0的
变化,只会出现0x00000001,0x00000002,0x00000003这样的数,而这样的数在寻址的时
候,都是指向了0x00000000起始的四个字节,所以啊,即使出现这样的数,都会自动对齐
到0x00000000了,因而才有上面一说。如此,也应该能够明白,在我们读写ram的时候,地
址的结尾只能是0,4,8,c了啊,^_^

那么究竟这个第二个地址的读取是通过一种什么机制呢,那就是PC,也就是Program Coun
t,程序计数器,就是它,在复位或者上电时刻,指向了0地址,即PC=0x00000000,然后
,在指向第二条指令的时候,它做了这样一个运算,PC=PC+4,很简单吧;但是!,因为
2440是三级流水线结构,PC的值就一定小心啊,下面来讲讲为什么
三级流水线,故名思义,就是一个时刻做三件事情,对于2440来说,那就是取指,译码,
执行
取指 译码 执行。。。
   取指 译码 执行。。。
             取指 译码 执行。。。
那么问一个问题,PC究竟是指向取指呢,译码呢,还是执行,^_^,对了,取指令!!由此
便带来一个问题,当前指令执行的时候,PC的值已经不是当前指令所在的地址了,而是
当前地址+8
   0x00000000
   0x00000004        ---假设为当前执行的指令地址
   0x00000008
PC-> 0x0000000c        PC指向的是这儿

上电之时,PC便首先指向了flash的0地址,这个地方的指令将被执行。那么我们的程序如
何才能被放在这个0地址呢,当然不能随便写,汇编中,这些都是有固定格式的,如下 :

   AREA Init,CODE,READONLY
   ENTRY
这个ENTRY便是表明,下面的程序为整个工程代码的入口点,至于如何放到flash的0地址,
那个就是flash烧写的工作了,不归我管,^_^

有了这样的入口,Init都要做些什么,先大概说说,包括几个部分吧,这些,也就是对
2440的初始化了
%定义入口地址
%建立异常向量表
%初始化存储器系统
%初始化堆栈
%初始化必要IO
%初始化中断系统要求的RAM向量
%开中断
%如有必要,改变处理器模式
%如有必要,改变处理器状态
%初始化C语言要求的存储器空间
%跳转到C去执行

建立异常向量表
我们知道,中断机制是PC机中一个非常重要的地方,中断节省CPU资源,加快了突发事件
的处理速度。在arm中,也差不多采取了类似的机制。PC中我们叫中断向量表,中断向量
表存放了一系列的跳转指令,当有中断产生的时候,系统便会自动到中断向量表查找相应
的中断向量号,然后根据中断号跳转到相应的地址去执行。
对于异常向量表,其实也是类似的功能,只不过对于一个arm来说,它上升到了工作模式
的高度,也就是说我们通常用的是用户模式,当有情况发生的时候,它要切换到相应的模
式下进行工作,比如中断,就是其中的一种!其他的还有管理模式,未定义指令模式,快
速中断模式,系统模式等等

异常向量表通常如下所示

b ResetHandler
b HandlerUndef
b HandlerSWI
b HandlerPabort
b HandlerDabort
b .
b IsrIRQ
b HandlerFIQ

那么,当有情况发生的时候,程序便会跳转到这个异常向量表的相应位置,执行相应的
跳转,如IRQ发生的时候,它就跳转到b IsrIRQ,进而执行这个跳转,去执行IsrIRQ标号
的代码

好了,知道了这个机制,便要关心这个表放在什么地方,才能让异常发生的时候,跳转
到这个表去执行相应的指令呢,呵呵,这肯定是放在一个特殊的地方,那就是0地址,
不过要注意了,这里0地址是哪里的0地址呢,呵呵
我们知道,异常的发生肯定是操作系统正在进行工作的时候,操作系统的工作是在
哪里进行??^_^,知道了,就是SDRAM,好了,操作系统在工作的时候,是不会在
返回到Nand Flash中去寻找咚咚的,明白了,这个异常向量表就是放在SDRAM的0地
址处,而且,一定要放在这个地方,这个地方也不能放别的东西,它就是放异常向量表

呵呵,插一段,我们要说说对于2440,它的启动流程是什么样子的,PC是怎么变化
的,简单说说吧

在Nand Flash中,bootloader,内核启动参数,内核,根文件系统是顺序存放的,并且,
bootloader是存放在0地址的,上电之后,PC就是指向这个0地址,并且开始执行,
bootloader要做很多事情,并且这些指令都是对CPU进行操作的,所以,很重要。而Init
就是bootloader中的一个部分,它的任务可以说是bootloader的子集;PC顺序执行,
首先关中断啊,初始化时钟啊等等,然后,将bootloader第二阶段的内容复制到SDRAM中
,包括Main主函数、内核和文件系统等复制过去,然后跳转到SDRAM中去执行,在执行
到跳转到内核去执行的时候,它要做一件事情,就是内存重映射,将PC重新定向到0地址
,并执行放在那儿的跳转指令……

转自http://space.baidu.com/%D2%FE%D0%CE%C8%CBlaigo/blog/item/7c2caadc02b87faacd1166b2.html

ARM指令中如何判断一个立即数是有效立即数(转载)


arm指令 立即数(一)
2011-04-13 16:55
在ARM处理器的汇编语言中,对指令语法格式中的<shifter_operand>的常数表达式有这样的规定:“该常数必须对应8位位图,即常数是由一个8位的常数循环移位偶数位得到的。
首先从ARM指令系统的语法格式说起。
一条ARM指令语法格式分为如下几个部分:
<opcode>{<cond>}{S} <Rd>,<Rn>{,<shifter_operand>}
其中,<>内的项是必须的,{}内的项是可选的,如<opcode>是指令助记符,是必须的,而{<cond>}为指令执行条件,是可选的,如果不写则使用默认条件AL(无条件执行)。
Opcode   指令助记符,如LDR,STR 等
Cond       执行条件,如EQ,NE 等
       S           是否影响CPSR 寄存器的值,书写时影响CPSR,否则不影响
       Rd          目标寄存器
Rn          第一个操作数的寄存器
shifter_operand      第二个操作数

其指令编码格式如下:

31-28
27-25
24-21
20  
19-16
15-12
11-0 (12位)
cond
001
opcode
S
Rn
Rd
shifter_operand

当第2 个操作数的形式为:#immed_8r常数表达式时“该常数必须对应8位位图,即常数是由一个8位的常数循环移位偶数位得到的。”
其意思是这样:
#immed_8r在芯片处理时表示一个32位数,但是它是由一个8位数(比如:01011010,即0x5A)通过循环移位偶数位得到(1000 0000 0000 0000 0000 0000 0001 0110,就是0x5A通过循环右移2位(偶数位)的到的)。
而1010 0000 0000 0000 0000 0000 0001 0110,就不符合这样的规定,编译时一定出错。因为你可能通过将1011 0101循环右移位得到它,但是不可能通过循环移位偶数位得到。1011 0000 0000 0000 0000 0000 0001 0110,也不符合这样的规定,很明显:1 0110 1011 有9位。
为什么要有这样的规定?
要从指令编码格式来解释(这就是我为什么一开始讲的是指令编码格式),仔细看表格中的shifter_operand所占的位数:12位。要用一个12位的编码来表示任意的32位数是绝对不可能的(12位数有2^12种可能,而32位数有2^32种)。
但是又要用12位的编码来表示32位数,怎么办?
只有在表示数的数量上做限制。通过编码来实现用12位的编码来表示32位数。
在12位的shifter_operand中:8位存数据,4位存移位的次数。
8位存数据:解释了“该常数必须对应8位位图”。
4位存移位的次数:解释了为什么只能移偶数位。4位只有16种可能值,而32位数可以循环移位32次(32种可能),那就只好限制:只能移偶数位(两位两位地移,好像一个16位数在移位,16种移位可能)。这样就解决了能表示的情况是实际情况一半的矛盾。
所以对#immed_8r常数表达式的限制是解决指令编码的第二个操作数位数不足以表示32位操作数的无奈之举,但在我看来:这个可以说是聪明的做法。因为如果直接用12位数来表示32位操作数,只能表示0 到(2^12-1)。大于(2^12-1)的数就没办法表示了。而且细细想来“8位存数据,4位存移位的次数”,应该是最好的组合了(我并未想过所有的组合,只是顺便试了几个)。

ARM指令第二操作数#immed_8r详解
大多数ARM通用数据处理指令有一个灵活的第2操作数(flexible second operand),这里这解释一下其中的一种格式,#immed_8r常量的表达式。常量必须对应于8位位图(pattern)。该位图在32位字中,被循环移位偶数位(0,2,4,...28,30)。合法常量0xff,0xff000,0xf000000f。非法常量:0x101,0xff04
ARM 在32位模式下,一条指令长度为32位,在上述数据处理指令中,操作数2为12位。所以像0x7f02这样的数,要两条指令才能完成。
MOV     R3, #0x7F00    ;E3 A0 3C 7F 该指令自己完成0x7f移位
ORR     R1, R3, #2
所以直接是找不到0x7f02的
关于循环移位,其实arm中只有循环右移(ROR)。0x7f到0x7f00是通过循环右移24次才实现的,这里每次移动2位所以是12次(0xc)
在 ARM 数据处理指令中, 当参与操作的第二操作数为立即数时, 每个立即数都是采用一个8位的常数循环右移偶数位而间接得到, 其中循环右移的位数有一个4位二进制的2倍表示. 则有效立即数可表示为: <immediate> := immed_8; 循环右移(2×rotate_imm). 其中: <immediate> 代表立即数, immed_8 代表8位常数,  即所谓的"8位图", rotate_imm 代表4位的循环右移值. 这样一来出现了一个问题: 尽管表示的范围变大了, 但是12位所能表现的数字的个数是一定的. 因此, ARM 规定并不是所有的32位常数都是合法的立即数, 只有通过上面的构造方法得到的才是合法的立即数, 编译的时候才不会报错.
举个例子吧.
0x3FC(0000 0000 0000 0000 0000 0011 1111 1100) 是由 0xff 循环右移 2 位得到的;
200(0000 0000 0000 0000 0000 0000 1100 1000) 是由 0xc8 循环右移 2 位得到的, 它们都是合法的.
而 0x1FE(0000 0000 0000 0000 0000 0001 1111 1110) 和
511(0000 0000 0000 0000 0000 0001 1111 1111) 无法看成是8位的常数循环右移偶数位而得到的, 因此是非法的.
指令操作数立即数时候,每个立即数由一个8位的常数循环右移偶数位得到。

<immediate>= immed_8 循环右移( 2*rotate_imm)

打个比如:
1.立即数0xF200是由0xCF2间接表示的,即是由8位的0xF2循环右移24(2*12)得到的
immed_8 == 0xF2;   rotate_imm == 0xC

2.立即数0x3F0是由0xE3F间接表示的,即是由8位的0x3F循环右移28(2*14)得到的
immed_8 == 0x3F;   rotate_imm == 0xE
或者
立即数0x3F0是由0xFFC间接表示的,即是由8位的0xFC循环右移30(2*15)得到的
immed_8 == 0xFC;   rotate_imm == 0xF

表示方法有好几种

PS:其实你没必要一个一个的算,只要利用LDR伪指令就可以了,例如:
ldr r1, =12345678
编译器自然会给你做工作,现实的编程中应该也是这个居多吧

比较下来, 我们可以这样总结:
  1. 判断一个数是否符合8位位图的原则, 首先看这个数的二进制表示中1的个数是否不超过8个. 如果不超过8个, 再看这n个1(n<=8)是否能同时放到8个二进制位中, 如果可以放进去, 再看这八个二进制位是否可以循环右移偶数位得到我们欲使用的数. 如果可以, 则此数符合8位位图原理, 是合法的立即数. 否则, 不符合.
  2. 无法表示的32位数, 只有通过逻辑或算术运算等其它途径获得了. 比如0xffffff00, 可以通过0x000000ff按位取反得到.
因此以后的编程中, 时刻检查用到的第二操作数是否符合8位位图是一件千万不能疏忽的事. 至于为什么要将这12位 operand2 "八四开", 这个问题就要请教大牛了.

计算机中的存储段类型

计算机中的存储管理中有三个数据段: 代码段(.text)、数据段(.data)以及BSS段(.bss).
这里首先区分一下.data与.bss,两个段存放的都是数据,区别是data段中的数据是带有初始化的,所以运行前其在代码段中的存储要包括段的大小以及初始化值,而bss段中的数据是不带有初始化值的,所以其在运行前在代码段中只包含段的大小信息,故未初始化的变量如果定义多了,代码会很小(其实仔细想想这是一句废话,变量不初始化,代码段中就不包含初始化信息,代码自然就小了).

note:其实仔细想想,编译器这样做是有一定的道理的。如果只用bss的话,有时候我们需要在变量中放入一些非常重要的初始化数据。如果我们都是用data段的话,本来一些不需要初始化的变量都要被迫地初始化一些值,这是对程序存储空间的浪费。

ARM中的RO、RW、ZI的内容

RO = 代码段(.text) + 常量数据段(.constdata) + ...(something I don't know now)
RW = 变量数据段(.data)
ZI = BSS数据段(.bss)

这里RO运行前运行后都只保存在flash中;RW运行前保存在flash中,运行后copy至RAM;ZI同RW一样,只是ZI在flash中没有初始化值。

arm汇编中的literal pools

        literal pools是一个用于存储32bit数据的字池,由于机器码的操作数operand2只有12位,所以其能操作的立即数是及其有限的,因此不得不使用一个literal pools来配合指令执行操作。这样一个ldr指令就有可能需要两个32bit的存储空间来完成一个任务。 如果一段代码中需要访问字池时,编译器首先寻找现有的字池,看看里面是否有想要的数据,如果没有则自动在代码段结尾处创建一个字池,当然也可以使用伪指令LTORG来自行创建一个字池。下面说一下字池的位置:
1、字池的位置一般是放在一个代码段的结束位置(一个代码段一般用AREA来定义),一般是在END的后面,或者下一个段(即下一个AREA指令)之前。
2、也可以使用伪指令LTORG自定义一个位置,但一般是在无条件跳转指令的后面,以保证literal pools不会被误当做可执行指令被执行。
3、还有一点,字池的位置要在指令的可执行位置范围内,即要在距离PC指针4k的范围内
(原因同样是因为operand2只有12位,即可寻址范围只有4k)。
    举例如下:
        start
                bl func1
                bl func2
        stop
                mov r0,#0x18
                ldr r1,=0x20026
        ;        SVC #0x123456
        func1
                ldr r0,=42
                ldr r1,=0x55555555
                ldr r2,=0xffffffff
                bx lr
                LTORG
        func2
                ldr r3,=0x55555555
                ldr r4,=0x66666666
                bx lr
        LargeTable
                SPACE 4200
                END
    反汇编可以看见
           29 00000018 E3E02000        ldr     r2,=0xffffffff
           30 0000001C E12FFF1E        bx      lr
           31 00000020 00020026
                      55555555         LTORG
           32 00000028         func2
     subroutine结尾处,bx lr后面使用了两个32bit的存储单元用来存放stop中的0x20026以及func1中的0x55555555.(0xffffffff可以用指令mvn解决),但是该段代码编译后会在指令ldr r4,=0x66666666处产生一个错误,即literal pools is too distant, use LTORG to assemble it within 4KB。即literal pools超出可寻址范围4kB。
     如果此时将LargeTable后面的SPACE 4200改成4092(因为bx lr要占用一个32bit空间).
                LargeTable
                SPACE 4092
                END
     就不会出现上面的错误了。

adr与ldr的区别

adr与ldr r0, =label的区别:
adr 和 ldr r0, =label(这里不包括ldr的一般用法)都是pseudo-instruction。
adr r0, label与ldr r0, =label实际上实现的功能都是一样儿的,都是将label的地址存放到r0中,但是由于adr中用的是相对地址且使用一个汇编指令完成,故其寻址范围限制在4k的范围内。但是ldr则不同,由于其使用了literal pools,寻址范围可以在4G的任意范围(但是切记literal pools的位置仍然要在4k之内)。如果说两者之间有什么不同的话,那就是:使用ldr要比使用adr浪费一些存储空间(如果label距离PC不是很远的情况下,使用adr是合理的)。

使用arm的启动代码2440init.s来举例如下:
代码未作任何修改的代码如下:
copy_proc_beg
        adr        r0, ResetEntry
        ldr        r2, BaseOfROM
        cmp        r0, r2
        ldreq      r0, TopOfROM
        beq        InitRam      
        ldr        r3, TopOfROM
其反汇编结果如下:
   copy_proc_beg
        0x00000268:    e24f0f9c    ..O.    SUB      r0,pc,#0x270 ; #0
        0x0000026c:    e59f2140    @!..    LDR      r2,0x3b4
        0x00000270:    e1500002    ..P.    CMP      r0,r2
        0x00000274:    059f013c    <...    LDREQ    r0,0x3b8
        0x00000278:    0afffffe    ....    BEQ      InitRam  ; 0x298
        0x0000027c:    e59f3134    41..    LDR      r3,0x3b8
可见此时r0的值正好是(pc+8-270)=0x0(至于这里为什么加8请看后面),即ResetEntry的位置。
将adr r0, ResetEntry改写成ldr r0, =ResetEntry后代码如下:
copy_proc_beg
        ldr            r0, =ResetEntry
        ldr            r2, BaseOfROM
        cmp        r0, r2
        ldreq       r0, TopOfROM
        beq         InitRam      
        ldr            r3, TopOfROM
反汇编结果如下:
   copy_proc_beg
        0x00000268:    e59f00f0    ....    LDR      r0,0x360
        0x0000026c:    e59f2144    D!..    LDR      r2,0x3b8
        0x00000270:    e1500002    ..P.    CMP      r0,r2
        0x00000274:    059f0140    @...    LDREQ    r0,0x3bc
        0x00000278:    0afffffe    ....    BEQ      InitRam  ; 0x298
        0x0000027c:    e59f3138    81..    LDR      r3,0x3bc
可见这里是将0x360处的值赋给了r0,而0x360处在literal pools中,如下:
    $d(表示literal pools位置)
        0x00000328:    4a000008    ...J    DCD    1241513992
        0x0000032c:    4a00001c    ...J    DCD    1241514012
        0x00000330:    00007fff    ....    DCD    32767
        0x00000334:    4c000014    ...L    DCD    1275068436
        0x00000338:    4c000008    ...L    DCD    1275068424
        0x0000033c:    00038022    "...    DCD    229410
        0x00000340:    4c000004    ...L    DCD    1275068420
        0x00000344:    0005c011    ....    DCD    376849
        0x00000348:    560000b4    ...V    DCD    1442840756
        0x0000034c:    56000050    P..V    DCD    1442840656
        0x00000350:    56000058    X..V    DCD    1442840664
        0x00000354:    56000054    T..V    DCD    1442840660
        0x00000358:    000055aa    .U..    DCD    21930
        0x0000035c:    00000268    h...    DCD    616
        0x00000360:    00000000    ....    DCD    0
        0x00000364:    000002c8    ....    DCD    712
        0x00000368:    00000000    ....    DCD    0
        0x0000036c:    000000d8    ....    DCD    216
        0x00000370:    33ff5c00    .\.3    DCD    872373248
        0x00000374:    33ff6000    .`.3    DCD    872374272
        0x00000378:    33ff7000    .p.3    DCD    872378368
        0x0000037c:    33ff8000    ...3    DCD    872382464
        0x00000380:    33ff5800    .X.3    DCD    872372224
此处的值正好位0x0,即ResetEntry的位置。
在程序的423行,可以看到有一个LTORG伪指令,正是由于这个原因,编译器才会在0x00000328位置开始建立literal pools。有关literal pools可以参考http://blog.csdn.net/caimingda1987/article/details/6662893。




前面提到pc指针默认加8的原因如下(转载):


2440是三级流水线结构,下面来讲讲为什么三级流水线,故名思义,就是一个时刻做三件事情,对于2440来说,那就是取指,译码,执行
取指 译码 执行。。。
   取指 译码 执行。。。
             取指 译码 执行。。。
那么问一个问题,PC究竟是指向取指呢,译码呢,还是执行,由此便带来一个问题,当前指令执行的时候,PC的值已经不是当前指令所在的地址了,而是
当前地址+8
   0x00000000
   0x00000004        ---假设为当前执行的指令地址
   0x00000008
PC-> 0x0000000c        PC指向的是这儿

Chapter 3 — The Molt

(This story is written by me and I will be posting it on Royal Road. Profile: https://www.royalroad.com/profile/1129550/fictions) Six fifty ...