Главная » Просмотр файлов » Volume 1 Application Programming

Volume 1 Application Programming (794095), страница 19

Файл №794095 Volume 1 Application Programming (Intel and AMD manuals) 19 страницаVolume 1 Application Programming (794095) страница 192019-04-28СтудИзба
Просмтор этого файла доступен только зарегистрированным пользователям. Но у нас супер быстрая регистрация: достаточно только электронной почты!

Текст из файла (страница 19)

This frame pointer is saved in a temporary register. If the depth operand is greaterthan one, the array of depth-1 frame pointers of procedures with smaller nesting level is pushed ontothe stack. This array is copied from the stack frame of the calling procedure, and it is addressed by theGeneral-Purpose Programming45AMD64 Technology24592—Rev. 3.13—July 2007rBP register from the calling procedure. If the depth operand is greater than zero, the saved framepointer of the current procedure is pushed onto the stack (forming an array of depth frame pointers).Finally, the saved value of the frame pointer is copied to the rBP register, and the rSP register isdecremented by the value of the first operand, allocating space for local variables used in theprocedure. See “Stack Operations” on page 44 for a parameter-passing instruction sequence usingPUSH that is equivalent to ENTER.The LEAVE instruction removes local variables and the array of frame pointers, allocated by theprevious ENTER instruction, from the stack frame.

This is accomplished by the following two steps:first, the value of the frame pointer is copied from the rBP register to the rSP register. This releases thespace allocated by local variables and an array of frame pointers of procedures with smaller nestinglevels. Second, the rBP register is popped from the stack, restoring the previous value of the framepointer (or simply the value of the rBP register, if the depth operand is zero).

Thus, the LEAVEinstruction is equivalent to the following code:mov rSP, rBPpop rBP3.3.3 Data ConversionThe data-conversion instructions perform various transformations of data, such as operand-sizedoubling by sign extension, conversion of little-endian to big-endian format, extraction of sign masks,searching a table, and support for operations with decimal numbers.Sign Extension• CBW—Convert Byte to Word• CWDE—Convert Word to Doubleword• CDQE—Convert Doubleword to Quadword• CWD—Convert Word to Doubleword• CDQ—Convert Doubleword to Quadword• CQO—Convert Quadword to OctwordThe CBW, CWDE, and CDQE instructions sign-extend the AL, AX, or EAX register to the upper halfof the AX, EAX, or RAX register, respectively.

By doing so, these instructions create a double-sizeddestination operand in rAX that has the same numerical value as the source operand. The CBW,CWDE, and CDQE instructions have the same opcode, and the action taken depends on the effectiveoperand size.The CWD, CDQ and CQO instructions sign-extend the AX, EAX, or RAX register to all bit positionsof the DX, EDX, or RDX register, respectively. By doing so, these instructions create a double-sizeddestination operand in rDX:rAX that has the same numerical value as the source operand. The CWD,CDQ, and CQO instructions have the same opcode, and the action taken depends on the effectiveoperand size.46General-Purpose Programming24592—Rev. 3.13—July 2007AMD64 TechnologyFlags are not affected by these instructions. The instructions can be used to prepare an operand forsigned division (performed by the IDIV instruction) by doubling its storage size.Extract Sign Mask• MOVMSKPS—Extract Packed Single-Precision Floating-Point Sign Mask• MOVMSKPD—Extract Packed Double-Precision Floating-Point Sign MaskThe MOVMSKPS instruction moves the sign bits of four packed single-precision floating-point valuesin an XMM register to the four low-order bits of a general-purpose register, with zero-extension.MOVMSKPD does a similar operation for two packed double-precision floating-point values: itmoves the two sign bits to the two low-order bits of a general-purpose register, with zero-extension.The result of either instruction is a sign-bit mask.Translate• XLAT—Translate Table IndexThe XLAT instruction replaces the value stored in the AL register with a table element.

The initialvalue in AL serves as an unsigned index into the table, and the start (base) of table is specified by theDS:rBX registers (depending on the effective address size).This instruction is not recommended. The following instruction serves to replace it:MOV AL,[rBX + AL]ASCII Adjust.••••AAA—ASCII Adjust After AdditionAAD—ASCII Adjust Before DivisionAAM—ASCII Adjust After MultiplyAAS—ASCII Adjust After SubtractionThe AAA, AAD, AAM, and AAS instructions perform corrections of arithmetic operations with nonpacked BCD values (i.e., when the decimal digit is stored in a byte register). There are no instructionswhich directly operate on decimal numbers (either packed or non-packed BCD). However, the ASCIIadjust instructions correct decimal-arithmetic results.

These instructions assume that an arithmeticinstruction, such as ADD, was performed on two BCD operands, and that the result was stored in theAL or AX register. This result can be incorrect or it can be a non-BCD value (for example, when adecimal carry occurs). After executing the proper ASCII-adjust instruction, the AX register contains acorrect BCD representation of the result. (The AAD instruction is an exception to this, because itshould be applied before a DIV instruction, as explained below). All of the ASCII-adjust instructionsare able to operate with multiple-precision decimal values.AAA should be applied after addition of two non-packed decimal digits.

AAS should be applied aftersubtraction of two non-packed decimal digits. AAM should be applied after multiplication of two nonpacked decimal digits. AAD should be applied before the division of two non-packed decimalnumbers.General-Purpose Programming47AMD64 Technology24592—Rev. 3.13—July 2007Although the base of the numeration for ASCII-adjust instructions is assumed to be 10, the AAM andAAD instructions can be used to correct multiplication and division with other bases.BCD Adjust• DAA—Decimal Adjust after Addition• DAS—Decimal Adjust after SubtractionThe DAA and DAS instructions perform corrections of addition and subtraction operations on packedBCD values. (Packed BCD values have two decimal digits stored in a byte register, with the higherdigit in the higher four bits, and the lower one in the lower four bits.) There are no instructions forcorrection of multiplication and division with packed BCD values.DAA should be applied after addition of two packed-BCD numbers.

DAS should be applied aftersubtraction of two packed-BCD numbers.DAA and DAS can be used in a loop to perform addition or subtraction of two multiple-precisiondecimal numbers stored in packed-BCD format. Each loop cycle would operate on correspondingbytes (containing two decimal digits) of operands.Endian Conversion• BSWAP—Byte SwapThe BSWAP instruction changes the byte order of a doubleword or quadword operand in a register, asshown in Figure 3-8. In a doubleword, bits 7–0 are exchanged with bits 31–24, and bits 15–8 areexchanged with bits 23–16.

In a quadword, bits 7–0 are exchanged with bits 63–56, bits 15–8 with bits55–48, bits 23–16 with bits 47–40, and bits 31–24 with bits 39–32. See the following illustration.3124 2316 158 703124 2316 158 70Figure 3-8.BSWAP Doubleword ExchangeA second application of the BSWAP instruction to the same operand restores its original value. Theresult of applying the BSWAP instruction to a 16-bit register is undefined.

To swap bytes of a 16-bitregister, use the XCHG instruction.The BSWAP instruction is used to convert data between little-endian and big-endian byte order.48General-Purpose Programming24592—Rev. 3.13—July 2007AMD64 Technology3.3.4 Load Segment RegistersThese instructions load segment registers.•••LDS, LES, LFS, LGS, LSS—Load Far PointerMOV segReg—Move Segment RegisterPOP segReg—Pop Stack Into Segment RegisterThe LDS, LES, LFD, LGS, and LSS instructions atomically load the two parts of a far pointer into asegment register and a general-purpose register. A far pointer is a 16-bit segment selector and a 16-bitor 32-bit offset.

The load copies the segment-selector portion of the pointer from memory into thesegment register and the offset portion of the pointer from memory into a general-purpose register.The effective operand size determines the size of the offset loaded by the LDS, LES, LFD, LGS, andLSS instructions. The instructions load not only the software-visible segment selector into the segmentregister, but they also cause the hardware to load the associated segment-descriptor information intothe software-invisible (hidden) portion of that segment register.The MOV segReg and POP segReg instructions load a segment selector from a general-purposeregister or memory (for MOV segReg) or from the top of the stack (for POP segReg) to a segmentregister.

These instructions not only load the software-visible segment selector into the segmentregister but also cause the hardware to load the associated segment-descriptor information into thesoftware-invisible (hidden) portion of that segment register.In 64-bit mode, the POP DS, POP ES, and POP SS instructions are invalid.3.3.5 Load Effective Address• LEA—Load Effective AddressThe LEA instruction calculates and loads the effective address (offset within a given segment) of asource operand and places it in a general-purpose register.LEA is related to MOV, which copies data from a memory location to a register, but LEA takes theaddress of the source operand, whereas MOV takes the contents of the memory location specified bythe source operand.

In the simplest cases, LEA can be replaced with MOV. For example:lea eax, [ebx]has the same effect as:mov eax, ebxHowever, LEA allows software to use any valid addressing mode for the source operand. For example:lea eax, [ebx+edi]loads the sum of EBX and EDI registers into the EAX register. This could not be accomplished by asingle MOV instruction.General-Purpose Programming49AMD64 Technology24592—Rev. 3.13—July 2007LEA has a limited capability to perform multiplication of operands in general-purpose registers usingscaled-index addressing. For example:lea eax, [ebx+ebx*8]loads the value of the EBX register, multiplied by 9, into the EAX register.3.3.6 ArithmeticThe arithmetic instructions perform basic arithmetic operations, such as addition, subtraction,multiplication, and division on integer operands.Add and Subtract• ADC—Add with Carry• ADD—Signed or Unsigned Add• SBB—Subtract with Borrow• SUB—Subtract• NEG—Two’s Complement NegationThe ADD instruction performs addition of two integer operands.

There are opcodes that add animmediate value to a byte, word, doubleword, or quadword register or a memory location. In theseopcodes, if the size of the immediate is smaller than that of the destination, the immediate is first signextended to the size of the destination operand. The arithmetic flags (OF, SF, ZF, AF, CF, PF) are setaccording to the resulting value of the destination operand.The ADC instruction performs addition of two integer operands, plus 1 if the carry flag (CF) is set.The SUB instruction performs subtraction of two integer operands.The SBB instruction performs subtraction of two integer operands, and it also subtracts an additional 1if the carry flag is set.The ADC and SBB instructions simplify addition and subtraction of multiple-precision integeroperands, because they correctly handle carries (and borrows) between parts of a multiple-precisionoperand.The NEG instruction performs negation of an integer operand.

Характеристики

Тип файла
PDF-файл
Размер
2,24 Mb
Материал
Тип материала
Высшее учебное заведение

Список файлов книги

Свежие статьи
Популярно сейчас
Почему делать на заказ в разы дороже, чем купить готовую учебную работу на СтудИзбе? Наши учебные работы продаются каждый год, тогда как большинство заказов выполняются с нуля. Найдите подходящий учебный материал на СтудИзбе!
Ответы на популярные вопросы
Да! Наши авторы собирают и выкладывают те работы, которые сдаются в Вашем учебном заведении ежегодно и уже проверены преподавателями.
Да! У нас любой человек может выложить любую учебную работу и зарабатывать на её продажах! Но каждый учебный материал публикуется только после тщательной проверки администрацией.
Вернём деньги! А если быть более точными, то автору даётся немного времени на исправление, а если не исправит или выйдет время, то вернём деньги в полном объёме!
Да! На равне с готовыми студенческими работами у нас продаются услуги. Цены на услуги видны сразу, то есть Вам нужно только указать параметры и сразу можно оплачивать.
Отзывы студентов
Ставлю 10/10
Все нравится, очень удобный сайт, помогает в учебе. Кроме этого, можно заработать самому, выставляя готовые учебные материалы на продажу здесь. Рейтинги и отзывы на преподавателей очень помогают сориентироваться в начале нового семестра. Спасибо за такую функцию. Ставлю максимальную оценку.
Лучшая платформа для успешной сдачи сессии
Познакомился со СтудИзбой благодаря своему другу, очень нравится интерфейс, количество доступных файлов, цена, в общем, все прекрасно. Даже сам продаю какие-то свои работы.
Студизба ван лав ❤
Очень офигенный сайт для студентов. Много полезных учебных материалов. Пользуюсь студизбой с октября 2021 года. Серьёзных нареканий нет. Хотелось бы, что бы ввели подписочную модель и сделали материалы дешевле 300 рублей в рамках подписки бесплатными.
Отличный сайт
Лично меня всё устраивает - и покупка, и продажа; и цены, и возможность предпросмотра куска файла, и обилие бесплатных файлов (в подборках по авторам, читай, ВУЗам и факультетам). Есть определённые баги, но всё решаемо, да и администраторы реагируют в течение суток.
Маленький отзыв о большом помощнике!
Студизба спасает в те моменты, когда сроки горят, а работ накопилось достаточно. Довольно удобный сайт с простой навигацией и огромным количеством материалов.
Студ. Изба как крупнейший сборник работ для студентов
Тут дофига бывает всего полезного. Печально, что бывают предметы по которым даже одного бесплатного решения нет, но это скорее вопрос к студентам. В остальном всё здорово.
Спасательный островок
Если уже не успеваешь разобраться или застрял на каком-то задание поможет тебе быстро и недорого решить твою проблему.
Всё и так отлично
Всё очень удобно. Особенно круто, что есть система бонусов и можно выводить остатки денег. Очень много качественных бесплатных файлов.
Отзыв о системе "Студизба"
Отличная платформа для распространения работ, востребованных студентами. Хорошо налаженная и качественная работа сайта, огромная база заданий и аудитория.
Отличный помощник
Отличный сайт с кучей полезных файлов, позволяющий найти много методичек / учебников / отзывов о вузах и преподователях.
Отлично помогает студентам в любой момент для решения трудных и незамедлительных задач
Хотелось бы больше конкретной информации о преподавателях. А так в принципе хороший сайт, всегда им пользуюсь и ни разу не было желания прекратить. Хороший сайт для помощи студентам, удобный и приятный интерфейс. Из недостатков можно выделить только отсутствия небольшого количества файлов.
Спасибо за шикарный сайт
Великолепный сайт на котором студент за не большие деньги может найти помощь с дз, проектами курсовыми, лабораторными, а также узнать отзывы на преподавателей и бесплатно скачать пособия.
Популярные преподаватели
Добавляйте материалы
и зарабатывайте!
Продажи идут автоматически
6417
Авторов
на СтудИзбе
307
Средний доход
с одного платного файла
Обучение Подробнее