|
Ушел с форума
16371 / 7683 / 1080
Регистрация: 11.11.2010
Сообщений: 13,757
|
||||||||||||
| 21.08.2014, 09:03 [ТС] | ||||||||||||
1
|
||||||||||||
| 21.08.2014, 09:03 | |
|
Ответы с готовыми решениями:
50
Неофициальная разработка Flat assembler версии 2.0.0 Flat assembler ругается на PROC
|
|
Ушел с форума
16371 / 7683 / 1080
Регистрация: 11.11.2010
Сообщений: 13,757
|
||||||||||||||||
| 21.08.2014, 09:03 [ТС] | ||||||||||||||||
|
Инструкции MMX оперируют со сжатыми целочисленными типами и используют регистры MMX, которыми являются нижние 64-битные части 80-битных регистров FPU. Поэтому инструкции MMX не могут использоваться в одно и то же время с инструкциями FPU. Они могут оперировать со сжатыми байтами (восемь 8-битных целых чисел), сжатыми словами (четыре 16-битных целых чисел) или сжатыми двойными словами (два 32-битных целых числа). Использование сжатых форматов позволяет совершать операции одновременно над многими данными.
0
|
||||||||||||||||
|
Ушел с форума
16371 / 7683 / 1080
Регистрация: 11.11.2010
Сообщений: 13,757
|
|||||||||||
| 21.08.2014, 09:05 [ТС] | |||||||||||
|
Расширение SSE добавляет больше инструкций MMX, а также представляет операции со сжатыми значениями одинарной точности с плавающей точкой. 128-битный сжатый формат одинарной точности содержит четыре значения одинарной точности с плавающей точкой. 128-битные регистры SSE созданы для поддержки операций этого типа данных.
0
|
|||||||||||
|
Ушел с форума
16371 / 7683 / 1080
Регистрация: 11.11.2010
Сообщений: 13,757
|
|||||||||||||||||||||||||||||||||||||||||||||||
| 21.08.2014, 09:06 [ТС] | |||||||||||||||||||||||||||||||||||||||||||||||
0
|
|||||||||||||||||||||||||||||||||||||||||||||||
|
Ушел с форума
16371 / 7683 / 1080
Регистрация: 11.11.2010
Сообщений: 13,757
|
|
| 21.08.2014, 09:06 [ТС] | |
|
SSE2 (англ. Streaming SIMD Extensions 2, потоковое SIMD-расширение процессора) — это SIMD (англ. Single Instruction, Multiple Data, Одна инструкция — множество данных) набор инструкций, разработанный Intel и впервые представленный в процессорах серии Pentium 4. SSE2 расширяет набор инструкций SSE с целью полного вытеснения MMX. Набор SSE2 добавил 144 новые команды к SSE, в котором было только 70 команд. SSE2 использует восемь 128-битных регистров (xmm0 до xmm7), включённых в архитектуру x86 с вводом расширения SSE, каждый из которых трактуется как 2 последовательных значения с плавающей точкой двойной точности. SSE2 включает в себя набор инструкций, который производит операции со скалярными и упакованными типами данных. SSE2 содержит инструкции для потоковой обработки целочисленных данных в тех же 128-битных xmm регистрах, что делает это расширение более предпочтительным для целочисленных вычислений, нежели использование набора инструкций MMX, появившегося гораздо раньше. SSE2 включает в себя две части – расширение SSE и расширение MMX.
SSE2 включает в себя ряд команд управления кэшем, предназначенных для минимизации загрязнения кэша при обработке объёмных потоков данных. SSE2 включает в себя сложные дополнения к командам преобразования чисел Технология SSE2 повышает эффективность The SSE2 extension introduces the operations on packed double precision floating point values, extends the syntax of MMX instructions, and adds also some new instructions. movapd and movupd transfer a double quad word operand containing packed double precision values from source operand to destination operand. These instructions are analogous to movaps and movups and have the same rules for operands. movlpd moves double precision value between the memory and the low quad word of SSE register. movhpd moved double precision value between the memory and the high quad word of SSE register. These instructions are analogous to movlps and movhps and have the same rules for operands. movmskpd transfers the most signicant bit of each of the two double precision values in the SSE register into low two bits of a general register. This instruction is analogous to movmskps and has the same rules for operands. movsd transfers a double precision value between source and destination operand (only the low quad word is trasferred). At least one of the operands have to be a SSE register, the second one can be also a SSE register or 64-bit memory location. Arithmetic operations on double precision values are: addpd, addsd, subpd, subsd, mulpd, mulsd, divpd, divsd, sqrtpd, sqrtsd, maxpd, maxsd, minpd, minsd, and they are analoguous to arithmetic operations on single precision values described in previous section. When the mnemonic ends with pd instead of ps, the operation is performed on packed two double precision values, but rules for operands are the same. When the mnemonic ends with sd instead of ss, the source operand can be a 64-bit memory location or a SSE register, the destination operand must be a SSE register and the operation is performed on double precision values, only low quad words of SSE registers are used in this case. andpd, andnpd, orpd and xorpd perform the logical operations on packed double precision values. They are analoguous to SSE logical operations on single prevision values and have the same rules for operands. cmppd compares packed double precision values and returns and returns a mask result into the destination operand. This instruction is analoguous to cmpps and has the same rules for operands. cmpsd performs the same operation on double precision values, only low quad word of destination register is aected, in this case source operand can be a 64-bit memory or SSE register. Variant with only two operands are obtained by attaching the condition mnemonic from table 2.3 to the cmp mnemonic and then attaching the pd or sd at the end. comisd and ucomisd compare the double precision values and set the ZF, PF and CF flags to show the result. The destination operand must be a SSE register, the source operand can be a 128-bit memory location or SSE register. shufpd moves any of the two double precision values from the destination operand into the low quad word of the destination operand, and any of the two values from the source operand into the high quad word of the destination operand. This instruction is analoguous to shufps and has the same rules for operand. Bit 0 of the third operand selects the value to be moved from the destination operand, bit 1 selects the value to be moved from the source operand, the rest of bits are reserved and must be zeroed. unpckhpd performs an unpack of the high quad words from the source and destination operands, unpcklpd performs an unpack of the low quad words from the source and destination operands. They are analoguous to unpckhps and unpcklps, and have the same rules for operands. cvtps2pd converts the packed two single precision floating point values to two packed double precision floating point values, the destination operand must be a SSE register, the source operand can be a 64-bit memory location or SSE register. cvtpd2ps converts the packed two double precision floating point values to packed two single precision floating point values, the destination operand must be a SSE register, the source operand can be a 128-bit memory location or SSE register. cvtss2sd converts the single precision floating point value to double precision floating point value, the destination operand must be a SSE register, the source operand can be a 32-bit memory location or SSE register. cvtsd2ss converts the double precision floating point value to single precision floating point value, the destination operand must be a SSE register, the source operand can be 64-bit memory location or SSE register. cvtpi2pd converts packed two double word integers into the the packed double precision floating point values, the destination operand must be a SSE register, the source operand can be a 64-bit memory location or MMX register. cvtsi2sd converts a double word integer into a double precision floating point value, the destination operand must be a SSE register, the source operand can be a 32-bit memory location or 32-bit general register. cvtpd2pi converts packed double precision floating point values into packed two double word integers, the destination operand should be a MMX register, the source operand can be a 128-bit memory location or SSE register. cvttpd2pi performs the similar operation, except that truncation is used to round a source values to integers, rules for operands are the same. cvtsd2si converts a double precision floating point value into a double word integer, the destination operand should be a 32-bit general register, the source operand can be a 64-bit memory location or SSE register. cvttsd2si performs the similar operation, except that truncation is used to round a source value to integer, rules for operands are the same.
1
|
|
|
Ушел с форума
16371 / 7683 / 1080
Регистрация: 11.11.2010
Сообщений: 13,757
|
|||||||||||
| 21.08.2014, 10:18 [ТС] | |||||||||||
|
cvtps2dq and cvttps2dq convert packed single precision floating point values to packed four double word integers, storing them in the destination operand. cvtpd2dq and cvttpd2dq convert packed double precision floating point values to packed two double word integers, storing the result in the low quad word of the destination operand. cvtdq2ps converts packed four double word integers to packed single precision floating point values.
For all these instructions destination operand must be a SSE register, the source operand can be a 128-bit memory location or SSE register. cvtdq2pd converts packed two double word integers from the low quad word of the source operand to packed double precision floating point values, the source can be a 64-bit memory location or SSE register, destination has to be SSE register. movdqa and movdqu transfer a double quad word operand containing packed integers from source operand to destination operand. At least one of the operands have to be a SSE register, the second one can be also a SSE register or 128-bit memory location. Memory operands for movdqa instruction must be aligned on boundary of 16 bytes, operands for movdqu instruction don't have to be aligned. movq2dq moves the contents of the MMX source register to the low quad word of destination SSE register. movdq2q moves the low quad word from the source SSE register to the destination MMX register.
These instructions follow the same rules for operands as the general MMX operations described in 2.1.14. pslldq and psrldq perform logical shift left or right of the double quad word in the destination operand by the amount of bytes specied in the source operand. The destination operand should be a SSE register, source operand should be an 8-bit immediate value. punpckhqdq interleaves the high quad word of the source operand and the high quad word of the destination operand and writes them to the destination SSE register. punpcklqdq interleaves the low quad word of the source operand and the low quad word of the destination operand and writes them to the destination SSE register. The source operand can be a 128-bit memory location or SSE register. movntdq stores packed integer data from the SSE register to memory using non-temporal hint. The source operand should be a SSE register, the destination operand should be a 128-bit memory location. movntpd stores packed double precision values from the SSE register to memory using a non-temporal hint. Rules for operand are the same. movnti stores integer from a general register to memory using a non-temporal hint. The source operand should be a 32-bit general register, the destination operand should be a 32-bit memory location. maskmovdqu stores selected bytes from the rst operand into a 128-bit memory location using a non-temporal hint. Both operands should be a SSE registers, the second operand selects wich bytes from the source operand are written to memory. The memory location is pointed by DI (or EDI) register in the segment selected by DS and does not need to be aligned. clflush writes and invalidates the cache line associated with the address of byte specied with the operand, which should be a 8-bit memory location. lfence performs a serializing operation on all instruction loading from memory that were issued prior to it. mfence performs a serializing operation on all instruction accesing memory that were issued prior to it, and so it combines the functions of sfence (described in previous section) and lfence instructions. These instructions have no operands.
0
|
|||||||||||
|
Ушел с форума
16371 / 7683 / 1080
Регистрация: 11.11.2010
Сообщений: 13,757
|
|
| 21.08.2014, 10:18 [ТС] | |
|
SSE3 (PNI — Prescott New Instruction) — третья версия SIMD-расширения Intel, потомок SSE, SSE2 и MMX. Впервые представлено в ядре Prescott процессора Pentium 4. AMD предложила свою реализацию SSE3 для процессоров Athlon 64 (ядра Venice, San Diego и Newark). Набор SSE3 содержит 13 инструкций:
Prescott technology introduced some new instructions to improve the performance of SSE and SSE2 - this extension is called SSE3. fisttp behaves like the fistp instruction and accepts the same operands, the only dierence is that it always used truncation, irrespective of the rounding mode. movshdup loads into destination operand the 128-bit value obtained from the source value of the same size by lling the each quad word with the two duplicates of the value in its high double word. movsldup performs the same action, except it duplicates the values of low double words. The destination operand should be SSE register, the source operand can be SSE register or 128-bit memory location. movddup loads the 64-bit source value and duplicates it into high and low quad word of the destination operand. The destination operand should be SSE register, the source operand can be SSE register or 64-bit memory location. lddqu is functionally equivalent to movdqu with memory as source operand, but it may improve performance when the source operand crosses a cacheline boundary. The destination operand has to be SSE register, the source operand must be 128-bit memory location. addsubps performs single precision addition of second and fourth pairs and single precision substracion of the rst and third pairs of floating point values in the operands. addsubpd performs double precision addition of the second pair and double precision substraction of the rst pair of floating point values in the operand. haddps performs the addition of two single precision values within the each quad word of source and destination operands, and stores the results of such horizontal addition of values from destination operand into low quad word of destination operand, and the results from the source operand into high quad word of destination operand. haddpd performs the addition of two double precision values within each operand, and stores the result from destination operand into low quad word of destination operand, and the result from source operand into high quad word of destination operand. All these instructions need the destination operand to be SSE register, source operand can be SSE register or 128-bit memory location. monitor sets up an address range for monitoring of write-back stores. It need its three operands to be EAX, ECX and EDX register in that order. mwait waits for a write-back store to the address range set up by the monitor instruction. It uses two operands with additional parameters, rst being the EAX and second the ECX register. The functionality of SSE3 is further extended by the set of Supplemental SSE3 instructions (SSSE3). They generally follow the same rules for operands as all the MMX operations extended by SSE. phaddw and phaddd perform the horizontal additional of the pairs of adjacent values from both the source and destination operand, and stores the sums into the destination (sums from the source operand go into lower part of destination register). They operate on 16-bit or 32-bit chunks, respectively. phaddsw performs the same operation on signed 16-bit packed values, but the result of each addition is saturated. phsubw and phsubd analogously perform the horizontal substraction of 16-bit or 32-bit packed value, and phsubsw performs the horizontal substraction of signed 16-bit packed values with saturation. pabsb, pabsw and pabsd calculate the absolute value of each signed packed signed value in source operand and stores them into the destination register. They operator on 8-bit, 16-bit and 32-bit elements respectively. pmaddubsw multiplies signed 8-bit values from the source operand with the corresponding unsigned 8-bit values from the destination operand to produce intermediate 16-bit values, and every adjacent pair of those intermediate values is then added horizontally and those 16-bit sums are stored into the destination operand. pmulhrsw multiplies corresponding 16-bit integers from the source and destination operand to produce intermediate 32-bit values, and the 16 bits next to the highest bit of each of those values are then rounded and packed into the destination operand. pshufb shues the bytes in the destination operand according to the mask provided by source operand - each of the bytes in source operand is an index of the target position for the corresponding byte in the destination. psignb, psignw and psignd perform the operation on 8-bit, 16-bit or 32-bit integers in destination operand, depending on the signs of the values in the source. If the value in source is negative, the corresponding value in the destination register is negated, if the value in source is positive, no operation is performed on the corresponding value is performed, and if the value in source is zero, the value in destination is zeroed, too. palignr appends the source operand to the destination operand to form the intermediate value of twice the size, and then extracts into the destination register the 64 or 128 bits that are right-aligned to the byte oset specied by the third operand, which should be an 8-bit immediate value. This is the only SSSE3 instruction that takes three arguments.
0
|
|
|
Ушел с форума
16371 / 7683 / 1080
Регистрация: 11.11.2010
Сообщений: 13,757
|
|
| 22.08.2014, 08:41 [ТС] | |
|
2.1.18 AMD 3DNow!-инструкции 3DNow! — дополнительное расширение MMX. Причиной создания 3DNow! послужило стремление завоевать превосходство над процессорами производства компании Intel в области обработки мультимедийных данных. Технология 3DNow! ввела 21 новую команду процессора и возможность оперировать 32-битными вещественными типами в стандартных MMX-регистрах. Также были добавлены специальные инструкции, оптимизирующие переключение в режим MMX/3DNow! (femms, которая заменяла стандартную инструкцию emms) и работу с кэшем процессора. Технология 3DNow! расширяла возможности технологии MMX, не требуя введения новых режимов работы процессора и новых регистров. Начиная с микроархитектуры Bulldozer расширение не поддерживается (за исключением команды prefetch) Инструкции 3DNow!
These instructions follow the same rules as the general MMX operations, the destination operand should be a MMX register, the source operand can be a MMX register or 64–bit memory location. pavgusb computes the rounded averages of packed unsigned bytes. pmulhrw performs a signed multiply of the packed words, round the high word of each double word results and stores them in the destination operand. pi2fd converts packed double word integers into packed floating point values. pf2id converts packed floating point values into packed double word integers using truncation. pi2fw converts packed word integers into packed floating point values, only low words of each double word in source operand are used. pf2iw converts packed floating point values to packed word integers, results are extended to double words using the sign extension. pfadd adds packed floating point values. pfsub and pfsubr substracts packed floating point values, the first one substracts source values from destination values, the second one substracts destination values from the source values. pfmul multiplies packed floating point values. pfacc adds the low and high floating point values of the destination operand, storing the result in the low double word of destination, and adds the low and high floating point values of the source operand, storing the result in the high double word of destination. pfnacc substracts the high floating point value of the destination operand from the low, storing the result in the low double word of destination, and substracts the high floating point value of the source operand from the low, storing the result in the high double word of destination. pfpnacc substracts the high floating point value of the destination operand from the low, storing the result in the low double word of destination, and adds the low and high floating point values of the source operand, storing the result in the high double word of destination. pfmax and pfmin compute the maximum and minimum of floating point values. pswapd reverses the high and low double word of the source operand. pfrcp returns an estimates of the reciprocals of floating point values from the source operand, pfrsqrt returns an estimates of the reciprocal square roots of floating point values from the source operand, pfrcpit1 performs the first step in the Newton–Raphson iteration to refine the reciprocal approximation produced by pfrcp instruction, pfrsqit1 performs the first step in the Newton–Raphson iteration to refine the reciprocal square root approximation produced by pfrsqrt instruction, pfrcpit2 performs the second final step in the Newton–Raphson iteration to refine the reciprocal approximation or the reciprocal square root approximation. pfcmpeq, pfcmpge and pfcmpgt compare the packed floating point values and sets all bits or zeroes all bits of the correspoding data element in the destination operand according to the result of comparison, first checks whether values are equal, second checks whether destination value is greater or equal to source value, third checks whether destination value is greater than source value. prefetch and prefetchw load the line of data from memory that contains byte specified with the operand into the data cache, prefetchw instruction should be used when the data in the cache line is expected to be modified, otherwise the prefetch instruction should be used. The operand should be an 8–bit memory location. femms performs a fast clear of MMX state. It has no operands.
0
|
|
|
Ушел с форума
16371 / 7683 / 1080
Регистрация: 11.11.2010
Сообщений: 13,757
|
||||||||||||
| 22.08.2014, 08:42 [ТС] | ||||||||||||
|
2.1.19 64-разрядные инструкции The AMD64 and EM64T architectures (we will use the common name x86–64 for them both) extend the x86 instruction set for the 64–bit processing. While legacy and compatibility modes use the same set of registers and instructions, the new long mode extends the x86 operations to 64 bits and introduces several new registers. You can turn on generating the code for this mode with the use64 directive. Each of the general purpose registers is extended to 64 bits and the eight whole new general purpose registers and также eight new SSE registers are added. See table 2.4 for the summary of new registers (only the ones that was not listed in table 1.2). The general purpose registers of smallers sizes are the low order portions of the larger ones. You can still access the ah, bh, ch and dh registers in long mode, but you cannot use them in the same instruction with any of the new registers. In general any instruction from x86 architecture, which allowed 16–bit or 32–bit operand sizes, in long mode allows также the 64–bit operands. The 64– bit registers should be used for addressing in long mode, the 32–bit addressing is также allowed, but it’s not possible to use the addresses based on 16–bit registers. Below are the samples of new operations possible in long mode on the example of mov instruction:
operator for address inside the square brackets. When no size operator is applied to address, assembler generates the optimal form automatically.
Three new type conversion instructions are available. The cdqe sign extends the double word in EAX into quad word and stores the result in RAX register. cqo sign extends the quad word in RAX into double quad word and stores the extra bits in the RDX register. These instructions have no operands. movsxd sign extends the double word source operand, being either the 32–bit register or memory, into 64–bit destination operand, which has to be register. No analogous instruction is needed for the zero extension, since it is done automatically by any operations on 32–bit registers, as noted in previous paragraph. And the movzx and movsx instructions, conforming to the general rule, can be used with 64–bit destination operand, allowing extension of byte or word values into quad words. All the binary arithmetic and logical instruction are promoted to allow 64–bit operands in long mode. The use of decimal arithmetic instructions in long mode is prohibited. The stack operations, like push and pop in long mode default to 64–bit operands and it’s not possible to use 32–bit operands with them. The pusha and popa are disallowed in long mode. The indirect near jumps and calls in long mode default to 64–bit operands and it’s not possible to use the 32–bit operands with them. On the other hand, the indirect far jumps and calls allow any operands that were allowed by the x86 architecture and также 80–bit memory operand is allowed (though only EM64T seems to implement such variant), with the first eight bytes defining the offset and two last bytes specifying the selector. The direct far jumps and calls are not allowed in long mode. The I/O instructions, in, out, ins and outs are the exceptional instructions that are not extended to accept quad word operands in long mode. But all other string operations are, and there are new short forms movsq, cmpsq, scasq, lodsq and stosq introduced for the variants of string operations for 64–bit string elements. The RSI and RDI registers are used by default to address the string elements. The lfs, lgs and lss instructions are extended to accept 80–bit source memory operand with 64–bit destination register (though only EM64T seems to implement such variant). The lds and les are disallowed in long mode. The system instructions like lgdt which required the 48–bit memory operand, in long mode require the 80–bit memory operand. The cmpxchg16b is the 64–bit equivalent of cmpxchg8b instruction, it uses the double quad word memory operand and 64–bit registers to perform the analoguous operation. swapgs is the new instruction, which swaps the contents of GS register and the KernelGSbase model–specific register (MSR address 0C0000102h). syscall and sysret is the pair of new instructions that provide the functionality similar to sysenter and sysexit in long mode, where the latter pair is disallowed.
0
|
||||||||||||
|
Ушел с форума
16371 / 7683 / 1080
Регистрация: 11.11.2010
Сообщений: 13,757
|
||||||||||||||||
| 22.08.2014, 08:43 [ТС] | ||||||||||||||||
|
2.1.20 Инструкции SSE4 SSE4 — новый набор команд микроархитектуры Intel Core, впервые реализованный в процессорах серии Penryn SSE4 состоит из 54 инструкций, 47 из них относят к SSE4.1 (они есть в процессорах Penryn). Полный набор команд (SSE4.1 и SSE4.2, то есть 47 + оставшиеся 7 команд) доступен в процессорах Intel с микроархитектурой Nehalem, которые были выпущены в середине ноября 2008 года и более поздних редакциях. Ни одна из SSE4 инструкций не работает с 64-х битными mmx регистрами (только с 128-ми битными xmm0-15). Добавлены инструкции, ускоряющие компенсацию движения в видеокодеках, быстрое чтение из USWC памяти, множество инструкций для упрощения векторизации программ компиляторами. Кроме того, в SSE4.2 добавлены инструкции обработки строк 8/16 битных символов, вычисления CRC32, popcnt. Впервые в SSE4 регистр xmm0 стал использоваться как неявный аргумент для некоторых инструкций. There are actually three dierent sets of instructions under the name SSE4. Intel de- signed two of them, SSE4.1 and SSE4.2, with latter extending the former into the full Intel's SSE4 set. On the other hand, the implementation by AMD includes only a few instructions from this set, but также contains some additional instructions, that are called the SSE4a set. The SSE4.1 instructions mostly follow the same rules for operands, as the basic SSE operations, so they require destination operand to be SSE register and source operand to be 128-bit memory location or SSE register, and some operations require a third operand, the 8-bit immediate value. pmulld performs a signed multiplication of the packed double words and stores the low double words of the results in the destination operand. pmuldq performs a two signed multiplications of the corresponding double words in the lower quad words of operands, and stores the results as packed quad words into the destination register. pminsb and pmaxsb return the minimum or maximum values of packed signed bytes, pminuw and pmaxuw return the minimum and maximum values of packed unsigned words, pminud, pmaxud, pminsd and pmaxsd return minimum or maximum values of packed unsigned or signed words. These instructions complement the instructions computing packed minimum or maximum introduced by SSE. ptest sets the ZF ag to one when the result of bitwise AND of the both operands is zero, and zeroes the ZF otherwise. It также sets CF ag to one, when the result of bitwise AND of the destination operand with the bitwise NOT of the source operand is zero, and zeroes the CF otherwise. pcmpeqq compares packed quad words for equality, and fills the corresponding elements of destination operand with either ones or zeros, depending on the result of comparison. packusdw converts packed signed double words from both the source and destination operand into the unsigned words using saturation, and stores the eight resulting word values into the destination register. phminposuw finds the minimum unsigned word value in source operand and places it into the lowest word of destination operand, setting the remaining upper bits of destination to zero. roundps, roundss, roundpd and roundsd perform the rounding of packed or individual oating point value of single or double precision, using the rounding mode specified by the third operand.
mpsadbw calculates multiple sums of absolute dierences of unsigned bytes. The third operand controls, with value in bits 0-1, which of the four-byte blocks in source operand is taken to calculate the absolute dierencies, and with value in bit 2, at which of the two first four-byte block in destination operand start calculating multiple sums. The sum is calculated from four absolute dierencies between the corresponding unsigned bytes in the source and destination block, and each next sum is calculated in the same way, but taking the four bytes from destination at the position one byte after the position of previous block. The four bytes from the source stay the same each time. This way eight sums of absolute dierencies are calculated and stored as packed word values into the destination operand. The instructions described in this paragraph follow the same rules for operands, as roundps instruction. blendps, blendvps, blendpd and blendvpd conditionally copy the values from source operand into the destination operand, depending on the bits of the mask provided by third operand. If a mask bit is set, the corresponding element of source is copied into the same place in destination, otherwise this position is destination is left unchanged. The rules for the first two operands are the same, as for general SSE instructions. blendps and blendpd need third operand to be 8-bit immediate, and they operate on single or double precision values, respectively. blendvps and blendvpd require third operand to be the XMM0 register.
0
|
||||||||||||||||
|
Ушел с форума
16371 / 7683 / 1080
Регистрация: 11.11.2010
Сообщений: 13,757
|
|||||||||||||||||||||||||||||||||||||
| 22.08.2014, 08:44 [ТС] | |||||||||||||||||||||||||||||||||||||
|
2.1.21 Инструкции AVX Advanced Vector Extensions (AVX) — расширение системы команд. AVX предоставляет различные улучшения, новые инструкции и новую схему кодирования машинных кодов. Новая схема кодирования инструкций VEX Ширина векторных регистров SIMD увеличивается со 128 (XMM) до 256 бит (регистры YMM0 — YMM15). Существующие 128-битные SSE инструкции будут использовать младшую половину новых YMM регистров, не изменяя старшую часть. Для работы с YMM регистрами добавлены новые 256-битные AVX инструкции. В будущем возможно расширение векторных регистров SIMD до 512 или 1024 бит. Например, процессоры с архитектурой Larrabee уже имеют векторные регистры (ZMM) шириной в 512 бит, и используют для работы с ними SIMD команды с MVEX и VEX префиксами, но при этом они не поддерживают AVX. Неразрушающие операции Набор AVX инструкций использует трехоперандный синтаксис. Например, вместо a = a + b можно использовать c = a + b, при этом регистр a остается неизмененным. В случаях, когда значение a используется дальше в вычислениях, это повышает производительность, так как избавляет от необходимости сохранять перед вычислением и восстанавливать после вычисления регистр, содержавший a, из другого регистра или памяти. Для большинства новых инструкций отсутствуют требования к выравниванию операндов в памяти. Однако рекомендуется следить за выравниванием на размер операнда, во избежание значительного снижения производительности. Набор инструкций AVX содержит в себе аналоги 128-битных SSE инструкций для вещественных чисел. При этом, в отличие от оригиналов, сохранение 128-битного результата будет обнулять старшую половину YMM регистра. 128-битные AVX инструкции сохраняют прочие преимущества AVX, такие как новая схема кодирования, трехоперандный синтаксис и невыровненный доступ к памяти. Рекомендуется отказаться от старых SSE инструкций в пользу новых 128-битных AVX инструкций, даже если достаточно двух операндов Новая схема кодирования Новая схема кодирования инструкций VEX использует VEX префикс. В настоящий момент существуют два VEX префикса, длиной 2 и 3 байта. Для 2-х байтного VEX префикса первый байт равен 0xC5, для 3-х байтного 0xC4. В 64-битном режиме первый байт VEX префикса уникален. В 32-битном режиме возникает конфликт с инструкциями LES и LDS, который разрешается старшим битом второго байта, он имеет значение только в 64-битном режиме, через неподдерживаемые формы инструкций LES и LDS. Длина существующих AVX инструкций, вместе с VEX префиксом, не превышает 11 байт. В следующих версиях ожидается появление более длинных инструкций. Также в спецификации AVX описана группа инструкций PCLMUL (Parallel Carry-Less Multiplication, Parallel CLMUL)
Подходит для интенсивных вычислений с плавающей точкой в мультимедиа программах и научных задачах. Там, где возможна более высокая степень параллелизма, увеличивает производительность с вещественными числами. The Advanced Vector Extensions introduce instructions that are new variants of SSE instructions, with new scheme of encoding that allows extended syntax having a destination operand separate from all the source operands. It также introduces 256-bit AVX registers, which extend up the old 128-bit SSE registers. Any AVX instruction that puts some result into SSE register, puts zero bits into high portion of the AVX register containing it. The AVX version of SSE instruction has the mnemonic obtained by prepending SSE instruction name with v. For any SSE arithmetic instruction which had a destination operand also being used as one of the source values, the AVX variant has a new syntax with three operands - the destination and two sources. The destination and first source can be SSE registers, and second source can be SSE register or memory. If the operation is performed on single pair of values, the remaining bits of first source SSE register are copied into the the destination register.
vdppd instruction has syntax extended to four operans, but it does not have a 256-bit version. The are a few instructions, namely vsqrtpd, vsqrtps, vrcpps and vrsqrtps, which can operate on 256-bit data size, but retained the syntax with only two operands, because they use data from only one source:
0
|
|||||||||||||||||||||||||||||||||||||
|
Ушел с форума
16371 / 7683 / 1080
Регистрация: 11.11.2010
Сообщений: 13,757
|
||||||||||||||||||||||||||
| 22.08.2014, 08:44 [ТС] | ||||||||||||||||||||||||||
0
|
||||||||||||||||||||||||||
|
Ушел с форума
16371 / 7683 / 1080
Регистрация: 11.11.2010
Сообщений: 13,757
|
|||||||||||||||||||||||||||||||||||||||||||||||||||
| 22.08.2014, 12:14 [ТС] | |||||||||||||||||||||||||||||||||||||||||||||||||||
|
The move and conversion instructions have mostly been promoted to allow 256-bit size operands in addition to the 128-bit variant with syntax identical to that from SSE version of the same instruction. Each of the vcvtdq2ps, vcvtps2dq and vcvttps2dq, vmovaps, vmovapd, vmovups, vmovupd, vmovdqa, vmovdqu, vlddqu, vmovntps, vmovntpd, vmovntdq, vmovsldup, vmovshdup, vmovmskps and vmovmskpd inherits the 128-bit syntax from SSE without any changes, and also allows a new form with 256-bit operands in place of 128-bit ones.
vmovlhps and vmovhlps have only 128-bit versions, and each takes three operands, which all must be SSE registers. vmovlhps copies two single precision values from the low quad word of second source register to the high quad word of destination register, and copies the low quad word of first source register into the low quad word of destination register. vmovhlps copies two single precision values from the high quad word of second source register to the low quad word of destination register, and copies the high quad word of first source register into the high quad word of destination register. vmovlps, vmovhps, vmovlpd and vmovhpd have only 128-bit versions and their syntax varies depending on whether memory operand is a destination or source. When memory is destination, the syntax is identical to the one of equivalent SSE instruction, and when memory is source, the instruction requires three operands, first two being SSE registers and the third one 64-bit memory. The value put into destination is then the value copied from first source with either low or high quad word replaced with value from second source (the memory operand).
vinsertps, vpinsrb, vpinsrw, vpinsrd, vpinsrq and vpblendw use a syntax with four operands, where destination and first source have to be SSE registers, and the third and fourth operand follow the same rules as second and third operand in the syntax of equivalent SSE instruction. Value stored in destination is the the value copied from first source with some data elements replaced with values extracted from the second source, analogously to the operation of corresponding SSE instruction.
vbroadcastf128 requires 128-bit memory as source, and AVX register as destination.
vextractf128 is the new instruction with three operands. The destination needs to be SSE register or 128-bit memory location, the source must be AVX register, and the third operand should be an immediate value. It extracts into destination one of the 128-bit units from source. The lowest bit of third operand specifies, which unit is extracted. vmaskmovps and vmaskmovpd are the new instructions with three operands that selectively store in destination the elements from second source depending on the sign bits of corresponding elements from first source. These instructions can operate on either 128-bit data (SSE registers) or 256-bit data (AVX registers). Either destination or second source has to be a memory location of appropriate size, the two other operands should be registers.
vperm2f128 is the new instruction with four operands, which selects 128-bit blocks of oating point data from first and second source according to the bit fields from fourth operand, and stores them in destination. Destination and first source need to be AVX registers, second source can be AVX register or 256-bit memory area, and fourth operand should be an immediate value.
vldmxcsr and vstmxcsr are the AVX versions of ldmxcsr and stmxcsr instructions. The rules for their operands remain unchanged.
0
|
|||||||||||||||||||||||||||||||||||||||||||||||||||
|
Ушел с форума
16371 / 7683 / 1080
Регистрация: 11.11.2010
Сообщений: 13,757
|
||||||||||||||||||||||||||
| 22.08.2014, 12:31 [ТС] | ||||||||||||||||||||||||||
|
2.1.22 Инструкции AVX2 AVX-512 расширяет AVX до векторов длиной 512-бит при помощи кодировки с префиксом EVEX. Расширение AVX-512 вводит 32 векторных регистра (ZMM), каждый по 512 бит, 8 регистров масок, 512-разрядные упакованные форматы для целых и дробных числе и операции над ними, тонкое управление режимами округления (позволяет переопределить глобальные настройки), операции broadcast, подавление ошибок в операциях с дробными числами, операции gather/scatter, быстрые математические операции, компактное кодирование больших смещений. AVX-512 предлагает совместимость с AVX, в том смысле, что программа может использовать инструкции как AVX, так и AVX-512 без снижения производительности. Регистры AVX (YMM0–YMM15) отображаются на младшие части регистров AVX-512 (ZMM0–ZMM15), по аналогии с SSE и AVX регистрами. The AVX2 extension allows all the AVX instructions operating on packed integers to use 256-bit data types, and introduces some new instructions as well. The AVX instructions that operate on packed integers and had only a 128-bit vari- ants, have been supplemented with 256-bit variants, and thus their syntax rules became analogous to AVX instructions operating on packed oating point types.
0
|
||||||||||||||||||||||||||
|
Ушел с форума
16371 / 7683 / 1080
Регистрация: 11.11.2010
Сообщений: 13,757
|
||||||||||||||||
| 24.08.2014, 06:07 [ТС] | ||||||||||||||||
|
There is a number of additional instruction set extensions related to AVX. They introduce new vector instructions (and sometimes также their SSE equivalents that use classic instruction encoding), and even some new instructions operating on general registers that use the AVX-like encoding allowing the extended syntax with separate destination and source operands. The CPU support for each of these instructions sets needs to be determined separately. The AES extension provides a specialized set of instructions for the purpose of cryptographic computations defined by Advanced Encryption Standard. Each of these instructions has two versions: the AVX one and the one with SSE-like syntax that uses classic encoding. Refer to the Intel manuals for the details of operation of these instructions. aesenc and aesenclast perform a single round of AES encryption on data from first source with a round key from second source, and store result in destination. The destination and first source are SSE registers, and the second source can be SSE register or 128-bit memory. The AVX versions of these instructions, vaesenc and vaesenclast, use the syntax with three operands, while the SSE-like version has only two operands, with first operand being both the destination and first source. aesdec and aesdeclast perform a single round of AES decryption on data from first source with a round key from second source. The syntax rules for them and their AVX versions are the same as for aesenc. aesimc performs the InvMixColumns transformation of source operand and store the result in destination. Both aesimc and vaesimc use only two operands, destination being SSE register, and source being SSE register or 128-bit memory location. aeskeygenassist is a helper instruction for generating the round key. It needs three operands: destination being SSE register, source being SSE register or 128-bit memory, and third operand being 8-bit immediate value. The AVX version of this instruction uses the same syntax. The CLMUL extension introduces just one instruction, pclmulqdq, and its AVX version as well. This instruction performs a carryless multiplication of two 64-bit values selected from first and second source according to the bit fields in immediate value. The destination and first source are SSE registers, second source is SSE register or 128- bit memory, and immediate value is provided as last operand. vpclmulqdq takes four operands, while pclmulqdq takes only three operands, with the first one serving both the role of destination and first source. The FMA (Fused Multiply-Add) extension introduces additional AVX instructions which perform multiplication and summation as single operation. Each one takes three operands, first one serving both the role of destination and first source, and the following ones being the second and third source. The mnemonic of FMA instruction is obtained by appending to vf prefix: first either m or nm to select whether result of multiplication should be taken as-is or negated, then either add or sub to select whether third value will be added to the product or substracted from the product, then either 132, 213 or 231 to select which source operands are multiplied and which one is added or substracted, and finally the type of data on which the instruction operates, either ps, pd, ss or sd. As it was with SSE instructions promoted to AVX, instructions operating on packed oating point values allow 128-bit or 256-bit syntax, in former all the operands are SSE registers, but the third one can также be a 128-bit memory, in latter the operands are AVX registers and the third one can также be a 256-bit memory. Instructions that compute just one oating point result need operands to be SSE registers, and the third operand can также be a memory, either 32-bit for single precision or 64-bit for double precision.
1
|
||||||||||||||||
|
Ушел с форума
16371 / 7683 / 1080
Регистрация: 11.11.2010
Сообщений: 13,757
|
||||||||||||||||||||||||||||||||||||||||||
| 27.08.2014, 10:22 [ТС] | ||||||||||||||||||||||||||||||||||||||||||
|
vpcmov copies bits from either first or second source into destination depending on the values of corresponding bits in the fourth operand (the selector). If the bit in selector is set, the corresponding bit from first source is copied into the same position in destination, otherwise the bit from second source is copied. Either second source or selector can be memory location, 128-bit or 256-bit depending on whether SSE registers or AVX registers are specified as the other operands.
vpermil2ps and vpermil2pd set the elements in destination register to zero or to a value selected from first or second source depending on the corresponding bit fields from the fourth operand (the selector) and the immediate value provided in fifth operand. Refer to the AMD manuals for the detailed explanation of the operation performed by these instructions. Each of the first four operands can be a register, and either second source or selector can be memory location, 128-bit or 256-bit depending on whether SSE registers or AVX registers are used for the other operands.
0
|
||||||||||||||||||||||||||||||||||||||||||
|
Ушел с форума
16371 / 7683 / 1080
Регистрация: 11.11.2010
Сообщений: 13,757
|
|||||||||||
| 27.08.2014, 10:24 [ТС] | |||||||||||
|
These BMI2 instructions follow the same rules for operands as andn. mulx is a BMI2 instruction which performs an unsigned multiplication of value from EDX or RDX register (depending on the size of specified operands) by the value from third operand, and stores the low half of result in the second operand, and the high half of result in the first operand, and it does it without aecting the ags. The third operand can be general register or memory, and both the destination operands have to be general registers.
0
|
|||||||||||
|
Ушел с форума
16371 / 7683 / 1080
Регистрация: 11.11.2010
Сообщений: 13,757
|
|
| 28.08.2014, 10:03 [ТС] | |
|
There is a number of additional instruction set extensions recognized by at assembler, and the general syntax of the instructions introduced by those extensions is provided here. For a detailed information on the operations performed by them, check out the manuals from Intel (for the VMX, SMX, XSAVE, RDRAND, FSGSBASE, INVPCID, HLE and RTM extensions) or AMD (for the SVM extension). The Virtual-Machine Extensions (VMX) provide a set of instructions for the man- agement of virtual machines. The vmxon instruction, which enters the VMX operation, requires a single 64-bit memory operand, which should be a physical address of memory region, which the logical processor may use to support VMX operation. The vmxoff instruction, which leaves the VMX operation, has no operands. The vmlaunch and vmresume, which launch or resume the virtual machines, and vmcall, which allows guest software to call the VM monitor, use no operands either. The vmptrld loads the physical address of current Virtual Machine Control Structure (VMCS) from its memory operand, vmptrst stores the pointer to current VMCS into address specified by its memory operand, and vmclear sets the launch state of the VMCS referenced by its memory operand to clear. These three instruction all require single 64-bit memory operand. The vmread reads from VCMS a field specified by the source operand and stores it into the destination operand. The source operand should be a general purpose register, and the destination operand can be a register of memory. The vmwrite writes into a VMCS field specified by the destination operand the value provided by source operand. The source operand can be a general purpose register or memory, and the destination operand must be a register. The size of operands for those instructions should be 64-bit when in long mode, and 32-bit otherwise. The invept and invvpid invalidate the translation lookaside buers (TLBs) and paging-structure caches, either derived from extended page tables (EPT), or based on the virtual processor identifier (VPID). These instructions require two operands, the first one being the general purpose register specifying the type of invalidation, and the second one being a 128-bit memory operand providing the invalidation descriptor. The first operand should be a 64-bit register when in long mode, and 32-bit register otherwise. The Safer Mode Extensions (SMX) provide the functionalities available throught the getsec instruction. This instruction takes no operands, and the function that is executed is determined by the contents of EAX register upon executing this instruction. The Secure Virtual Machine (SVM) is a variant of virtual machine extension used by AMD. The skinit instruction securely reinitializes the processor allowing the startup of trusted software, such as the virtual machine monitor (VMM). This instruction takes a single operand, which must be EAX, and provides a physical address of the secure loader block (SLB). The vmrun instruction is used to start a guest virtual machine, its only operand should be an accumulator register (AX, EAX or RAX, the last one available only in long mode) providing the physical address of the virtual machine control block (VMCB). The vmsave stores a subset of processor state into VMCB specified by its operand, and vmload loads the same subset of processor state from a specified VMCB. The same operand rules as for the vmrun apply to those two instructions. vmmcall allows the guest software to call the VMM. This instruction takes no operands. stgi set the global interrupt ag to 1, and clgi zeroes it. These instructions take no operands. invlpga invalidates the TLB mapping for a virtual page specified by the first operand (which has to be accumulator register) and address space identifier specified by the second operand (which must be ECX register). The XSAVE set of instructions allows to save and restore processor state components. xsave and xsaveopt store the components of processor state defined by bit mask in EDX and EAX registers into area defined by memory operand. xrstor restores from the area specified by memory operand the components of processor state defined by mask in EDX and EAX. The xsave64, xsaveopt64 and xrstor64 are 64-bit versions of these instructions, allowed only in long mode. xgetbv read the contents of 64-bit XCR (extended control register) specified in ECX register into EDX and EAX registers. xsetbv writes the contents of EDX and EAX into the 64-bit XCR specified by ECX register. These instructions have no operands. The RDRAND extension introduces one new instruction, rdrand, which loads the hardware-generated random value into general register. It takes one operand, which can be 16-bit, 32-bit or 64-bit register (with the last one being allowed only in long mode). The FSGSBASE extension adds long mode instructions that allow to read and write the segment base registers for FS and GS segments. rdfsbase and rdgsbase read the corresponding segment base registers into operand, while wrfsbase and wrgsbase write the value of operand into those register. All these instructions take one operand, which can be 32-bit or 64-bit general register. The INVPCID extension adds invpcid instruction, which invalidates mapping in the TLBs and paging caches based on the invalidation type specified in first operand and PCID invalidate descriptor specified in second operand. The first operands should be 32-bit general register when not in long mode, or 64-bit general register when in long mode. The second operand should be 128-bit memory location. The HLE and RTM extensions provide set of instructions for the transactional management. The xacquire and xrelease are new prefixes that can be used with some of the instructions to start or end lock elision on the memory address specified by prefixed instruction. The xbegin instruction starts the transactional execution, its operand is the address a fallback routine that gets executes in case of transaction abort, specified like the operand for near jump instruction. xend marks the end of transcational execution region, it takes no operands. xabort forces the transaction abort, it takes an 8-bit immediate value as its only operand, this value is passed in the highest bits of EAX to the fallback routine. xtest checks whether there is transactional execution in progress, this instruction takes no operands.
0
|
|
|
Ушел с форума
16371 / 7683 / 1080
Регистрация: 11.11.2010
Сообщений: 13,757
|
||||||||||||||||||||||||||
| 29.08.2014, 06:21 [ТС] | ||||||||||||||||||||||||||
|
2.1 Директивы управления Этот параграф описывает директивы, которые управляют процессом ассемблирования. Эти директивы выполняются во время ассемблирования и могут делать так, чтобы некоторые блоки инструкций ассемблировались по-разному или не ассемблировались вовсе. Численные константы определяются с помощью директивы =. Сначала пишется имя константы, затем директива = и выражение, определяющее значение константы. Значением может быть число или адрес, но в отличие от меток, в численных константах нельзя использовать регистровую адресацию. В целом же численные константы ведут себя, так же как и метки. Вы даже можете обратиться к константе до того, как она была определена (forward-reference). Hо есть и другой вид численных констант. Если определить константу с именем, которое уже использовалось ранее для определения численной константы, то ассемблер будет рассматривать данную константу как переменную времени транслирования (assembly-time variable). Такой переменной можно присваивать новые значения, но, по вполне понятной причине, на нее нельзя ссылаться до ее определения. Давайте рассмотрим два варианта численных констант в одном примере:
Значению численной константы может предшествовать оператор размера, гарантирующий, что значение находится в допустимом для заданного размера диапазоне. Оператор размера может также повлиять на некоторые вычисления с константами. Следующий пример определяет две разные константы: первую размером 8 бит, вторую - 32 бита
С помощью директивы "if" можно ассемблировать или не ассемблировать блок инструкций в зависимости от выполнения условия. За ней должно следовать логическое выражение, определяющее условие. Инструкции на следующих строках ассемблируются, только если это условие выполняется, иначе они пропускаются. Опциональная директива "elseif" со следующим за ней логическим выражением, определяющим дополнительное условие, начинает следующий блок инструкций, который ассемблируется, если предыдущие условия не выполняются, а данное дополнительное условие выполняется. Опциональная директива "else" начинает блок инструкций, которые ассемблируются, если не выполняется ни одно из условий. "end if" заканчивает последний блок инструкций. Вы должны помнить, что директива "if" обрабатывается на стадии ассемблирования и поэтому не влияет на директивы препроцессора, такие как определения символьных констант и макроинструкции - когда ассемблер распознает директиву "if", весь препроцессинг уже закончен. Логическое выражение состоит из логических значений и логических операторов. Логические операторы выглядят так: "~" для логического отрицания, "&" для логического И, "|" для логического ИЛИ. Отрицание имеет высший приоритет. Логическое значение может быть числовым выражением, оно будет считаться ложным в случае равенства нулю, иначе оно будет истинным. Для создания логического значения можно сравнить два числовых выражения, используя один из следующих операторов: "=" (равно), "<" (меньше), ">" (больше), "<=" (меньше или равно), ">=" (больше или равно), "<>" (не равно). "used" со следующим за ним символом имени, это логическое значение, которое проверяет, использовался ли где-нибудь данный символ (он возвращает правильный результат даже если символ используется только после этой проверки). За оператором "defined" может следовать любое выражение, обычно это только одно символьное имя; этот оператор проверяет, содержит ли данное выражение исключительно символы, определенные в коде, и доступные из текущей позиции. Следующий простой пример использует константу "count" которая должна быть определена где-то в коде:
Также есть операторы, которые позволяют сравнивать значения, которые представляют собой последовательности символов. "eq" проверяет такие значения на тождественность. Оператор "in" проверяет, принадлежит ли данное значение к списку значений, следующему за оператором. Список должен быть заключен между символами "<" и ">", а его члены должны быть разделены запятыми. Символы считаются одинаковыми, если они имеют одно и то же значение для ассемблера - например, "pword" и "fword" для ассемблера одинаковы поэтому не различаются вышеуказанными операторами. Так же "16 eq 10h" является истиной, однако "16 eq 10+4" нет. Оператор "eqtype" имеют ли сравниваемые значения одинаковую структуру, и принадлежат ли структурные элементы одному типу. Различаемые типы включают в себя числовые выражения, строки, заключенные в кавычки, значения с плавающей точкой, адресные выражения (выражения в квадратных скобках или предваренные оператором "ptr"), мнемоники инструкций, регистры, операторы размера, операторы перехода и операторы типа кода. И каждый из специальных символов, действующих как разделители, такой как запятая или двоеточие, это отдельный тип сам по себе. Например, два значения, каждое из которых состоит из имени регистра и числового выражения, разделенных запятой, будут распознаны как один тип, независимо от вида регистра и сложности числового выражения; за исключением строк, заключенных в кавычки и значений с плавающей точкой, которые относятся к специальным видом числовых выражений и распознаются как разные типы. Поэтому условие "eax,16 eqtype fs,3+7" является истиной, но "eax,16 eqtype eax,1.6" - ложь.
0
|
||||||||||||||||||||||||||
|
Ушел с форума
16371 / 7683 / 1080
Регистрация: 11.11.2010
Сообщений: 13,757
|
|||||||||||||||||||||||||||||||||||||||||||||||||||
| 29.08.2014, 06:26 [ТС] | |||||||||||||||||||||||||||||||||||||||||||||||||||
|
"times" повторяет одну инструкцию указанное количество раз. За ней должно следовать числовое выражение, определяющее количество повторений, и инструкция, которую нужно повторять (опционально для того, чтобы отделить число и инструкцию, можно использовать двоеточие). Специальный символ "%", использующийся внутри инструкции, эквивалентен номеру текущего повтора. Например, "times 5 db %" определит пять байтов со значениями 1, 2, 3, 4, 5. Поддерживается также рекурсивное использование директивы "times", например, "times 3 times % db %" определит шесть байтов со значениями 1, 1, 2, 1, 2, 3. "repeat" повторяет целый блок инструкций. За ней должно следовать числовое выражение, определяющее количество повторений. Инструкции для повторения предполагаются на следующих строках, а заканчиваться блок должен директивой "end repeat", например:
Количество повторений может быть равным нулю, и в таком случае инструкции не будут ассемболироваться вовсе. "break" позволяет остановить повторение раньше и продолжить ассемблирование с первой строки после "end repeat". В сочетании с директивой "if" она позволяет остановить повторение при выполнении некоторого особого условия, например:
Добавлено через 5 минут "org" устанавливает адрес, по которому следующий за ней код должен появиться в памяти. За ней должно следовать числовое выражение, указывающее адрес. Эта директива начинает новое адресное пространство, следующий код сам по себе никуда не двигается, но все метки, определенные в нем и значение символа "$" изменяются как если бы он был бы помещен по этому адресу. Тем не менее обязанность поместить во время выполнения код по правильному адресу лежит на программисте. "load" позволяет определить константу двоичным значением, загруженным из уже сассемблированного кода. За директивой должно следовать имя константы, затем опционально оператор размера, затем оператор "from" и числовое выражение, определяющее валидный адрес в текущем адресном пространстве. Оператор размера здесь имеет необычное значение - он определяет, сколько байтов (до 8) должно быть загружено из двоичного значения константы. Если оператор размера не определен, загружается один байт (таким образом значение оказывается в пределах от 0 до 255). Загруженные данные не могут превосходить текущее смещение. "store" может модифицировать уже сгенерированный код заменой некоторых ранее сгенерированных байтов значением, задаваемым следующим за инструкцией числовым выражением. Перед этим выражением может идти оператор размера, определяющий, насколько длинное значение оно задает, то есть сколько будет сохранено байт. Если оператор размера не задан, подразумевается длина в один байт. Далее должен следовать оператор "at" и числовое выражение, указывающее валидный адрес в текущем адресном пространстве кода. По этому адресу будет сохранено задаваемое значение. Это директива для продвинутого применения и её следует использовать осторожно. Обе директивы "load" и "store" ограничены оперированием только в пределах текущего адресного пространства. Символ "$$" всегда равен базовому адресу в текущем адресном пространстве, а символ "$" - это адрес текущей позиции в нём, то есть эти два значения определяют границы действия директив "load" и "store". Сочетая директивы "load" и "store" можно делать вещи, такие как шифрование некоторого из уже сгенерированного кода. Например, для шифрования всего кода, сгенерированного в текущем адресном пространстве вы можете использовать такой блок директив:
"virtual" определяет виртуальные данные по указанному адресу. Эти данные не будут включены в файл вывода, но но метки, определенные здесь, могут использоваться в других частях кода. За этой директивой может следовать оператор "at" и числовое выражение, определяющее адрес виртуальных данных, иначе будет использован текущий адрес, что равносильно директиве "virtual at $". Инструкции определяемых данных должны быть расположены на следующих строках и заканчиваться директивой "end virtual". Блок виртуальных инструкций сам по себе независимое адресное пространство, и после того, как оно заканчивается, восстанавливается контекст предыдущего адресного пространства. Директива "virtual" может быть использована для создания объединения нескольких переменных, например:
Директива также может быть использована для определения меток некоторых структур, адресованных регистром, например:
Также может быть полезно объявление инструкций и значений данных внутри виртуально блока, так как директиву "load" можно использовать для загрузки в константы значений из виртуально сгенерированного кода. Эта директива должна быть использована после загружаемого кода, но до окончания виртуального блока, так как она может загружать значения только из того же адресного пространства. Например:
Все директивы "section", описанные в 2.4, также начинают новое адресное пространство. "align" выравнивает код или данные по указанной границе. За ней должно следовать числовое выражение, определяющее количество байтов, на кратность которому должен быть выровнен текущий адрес. Значение границы должно быть степенью двойки. Директива "align" заполняет байты, которые должны быть пропущены, чтобы совершить выравнивание, инструкциями "nop", и в это же время маркирует эту область как неинициализированные данные, то есть если её поместить среди других неинициализированных данных, это не займет места в файле вывода, выравнивание байтов происходит таким же образом. Если вам нужно заполнить область выравнивания какими-то другими значениями, вы можете сочетать "align" и "virtual", чтобы получить требуемый размер выравнивания и далее создать выравнивание самостоятельно, например:
"display" во время ассемблирования показывает сообщение. За ней должны следовать строка в кавычках или значения байтов, разделенные запятыми. Директива может быть использована для показа значений некоторых констант, например:
0
|
|||||||||||||||||||||||||||||||||||||||||||||||||||
| 29.08.2014, 06:26 | |
|
Помогаю со студенческими работами здесь
40
Flat Assembler Ошибка в flat assembler flat assembler массив Массив в Flat Assembler Как использовать Flat Assembler в Free Pascal? Искать еще темы с ответами Или воспользуйтесь поиском по форуму: |
|
Новые блоги и статьи
|
||||
|
Новый ноутбук
volvo 07.12.2025
Всем привет.
По скидке в "черную пятницу" взял себе новый ноутбук Lenovo ThinkBook 16 G7 на Амазоне:
Ryzen 5 7533HS
64 Gb DDR5
1Tb NVMe
16" Full HD Display
Win11 Pro
|
Музыка, написанная Искусственным Интеллектом
volvo 04.12.2025
Всем привет. Некоторое время назад меня заинтересовало, что уже умеет ИИ в плане написания музыки для песен, и, собственно, исполнения этих самых песен. Стихов у нас много, уже вышли 4 книги, еще 3. . .
|
От async/await к виртуальным потокам в Python
IndentationError 23.11.2025
Армин Ронахер поставил под сомнение async/ await. Создатель Flask заявляет: цветные функции - провал, виртуальные потоки - решение. Не threading-динозавры, а новое поколение лёгких потоков. Откат?. . .
|
Поиск "дружественных имён" СОМ портов
Argus19 22.11.2025
Поиск "дружественных имён" СОМ портов
На странице:
https:/ / norseev. ru/ 2018/ 01/ 04/ comportlist_windows/
нашёл схожую тему. Там приведён код на С++, который показывает только имена СОМ портов, типа,. . .
|
Сколько Государство потратило денег на меня, обеспечивая инсулином.
Programma_Boinc 20.11.2025
Сколько Государство потратило денег на меня, обеспечивая инсулином.
Вот решила сделать интересный приблизительный подсчет, сколько государство потратило на меня денег на покупку инсулинов.
. . .
|
|
Ломающие изменения в C#.NStar Alpha
Etyuhibosecyu 20.11.2025
Уже можно не только тестировать, но и пользоваться C#. NStar - писать оконные приложения, содержащие надписи, кнопки, текстовые поля и даже изображения, например, моя игра "Три в ряд" написана на этом. . .
|
Мысли в слух
kumehtar 18.11.2025
Кстати, совсем недавно имел разговор на тему медитаций с людьми. И обнаружил, что они вообще не понимают что такое медитация и зачем она нужна. Самые базовые вещи. Для них это - когда просто люди. . .
|
Создание Single Page Application на фреймах
krapotkin 16.11.2025
Статья исключительно для начинающих. Подходы оригинальностью не блещут.
В век Веб все очень привыкли к дизайну Single-Page-Application .
Быстренько разберем подход "на фреймах".
Мы делаем одну. . .
|
Фото: Daniel Greenwood
kumehtar 13.11.2025
|
Расскажи мне о Мире, бродяга
kumehtar 12.11.2025
— Расскажи мне о Мире, бродяга,
Ты же видел моря и метели.
Как сменялись короны и стяги,
Как эпохи стрелою летели.
- Этот мир — это крылья и горы,
Снег и пламя, любовь и тревоги,
И бескрайние. . .
|