информационная безопасность
без паники и всерьез
 подробно о проектеRambler's Top100
Атака на InternetПортрет посетителяSpanning Tree Protocol: недокументированное применение
BugTraq.Ru
Русский BugTraq
 Анализ криптографических сетевых... 
 Модель надежности двухузлового... 
 Специальные марковские модели надежности... 
 Бэкдор в xz/liblzma, предназначенный... 
 Три миллиона электронных замков... 
 Doom на газонокосилках 
главная обзор RSN блог библиотека закон бред форум dnet о проекте
bugtraq.ru / форум / dnet
Имя Пароль
ФОРУМ
все доски
FAQ
IRC
новые сообщения
site updates
guestbook
beginners
sysadmin
programming
operating systems
theory
web building
software
hardware
networking
law
hacking
gadgets
job
dnet
humor
miscellaneous
scrap
регистрация





Легенда:
  новое сообщение
  закрытая нитка
  новое сообщение
  в закрытой нитке
  старое сообщение
  • Напоминаю, что масса вопросов по функционированию форума снимается после прочтения его описания.
  • Новичкам также крайне полезно ознакомиться с данным документом.
По поводу Pentium 4 20.03.02 22:25  Число просмотров: 1675
Автор: Mishka Статус: Незарегистрированный пользователь
<"чистая" ссылка>
> Опять неверно. Это же вроде прописные истины. Так было в
> MMX.
> Регистры MMX есть регистры FPU x87 поэтому одновременно
> использовать
> MMX и FPU команды, мягко говоря, не рекомендуется. Да, и
> MMX функционально не использует FPU. Для него есть
> отдельный Execution Unit.

Посмотрел доки на П4:

Intel® Pentium® 4 Processor Optimization Reference Manual
http://developer.intel.com/design/pentium4/manuals/248966.htm

Page 4-2 (162)

General Rules on SIMD Integer Code

The overall rules and suggestions are as follows:

- Do not intermix 64-bit SIMD integer instructions with x87 floating-point
instructions. See “Using SIMD Integer with x87 Floating-point” section. Note that
all of the SIMD integer instructions can be intermixed without penalty.

- When writing SSE2 code that works with both integer and floating-point data, use
the subset of SIMD convert instructions or load/store instructions to ensure that the
input operands in XMM registers contain properly defined data type to match the
instruction. Code sequences containing cross-typed usage will produce the same
result across different implementations, but will incur a significant performance
penalty. Using SSE or SSE2 instructions to operate on type-mismatched SIMD
data in the XMM register is strongly discouraged.

- Use the optimization rules and guidelines described in Chapters 2 and 3 that apply
both to the Pentium 4 processor in general and to using the SIMD integer
instructions.

- Incorporate the prefetch instruction whenever possible (for details, refer to
Chapter 6, “Optimizing Cache Usage for Intel® Pentium® 4 Processors”).

- Emulate conditional moves by using masked compares and logicals instead of
using conditional branches.


Using SIMD Integer with x87 Floating-point

All 64-bit SIMD integer instructions use the MMX registers, which share register state
with the x87 floating-point stack. Because of this sharing, certain rules and
considerations apply. Instructions which use the MMX registers cannot be freely
intermixed with x87 floating-point registers. Care must be taken when switching
between using 64-bit SIMD integer instructions and x87 floating-point instructions
(see Using the EMMS Instruction section below).

The SIMD floating-point operations and 128-bit SIMD integer operations can be
freely intermixed with either x87 floating-point operations or 64-bit SIMD integer
operations. The SIMD floating-point operations and 128-bit SIMD integer operations
Intel Pentium 4 and Intel Xeon Processor Optimization Optimizing for SIMD Integer Applications 4
use registers that are unrelated to the x87 FP / MMX registers. The emms instruction is
not needed to transition to or from SIMD floating-point operations or 128-bit SIMD
operations.


Из чего делаю вывод: MMX & SSE - FPU sharing, SSE2 - independent. Т.е. при работе с 128 битовыми целыми - все хорошо, а с 64 битовыми напряженка. При этом, насколько я понимаю, из описания и доки, то ССЕ2 с 64 не работает.

>
> Вообще говоря, каюсь, MMX содержит операции на 64битными
> целыми, но с указаными выше ограничениям. Прелесть SSE2 - в
> их отсутствии и в том,
> что можно делать одновременно 2 операции над 64битным целым
> или одну над 128битным, если это сдвиг. Это важная фича для
> RC5 на этапе key expansion.
>

Далее читаем:

Page 2-5 (56)

Optimize Instruction Selection

- Avoid longer latency instructions: shifts, integer multiplies and divides. Replace
them with alternate code sequences (e.g. adds instead of shifts, and shifts instead
of multiplies).

- Use the lea instruction and the full range of addressing modes to do address
calculation.

- Some types of stores use more µops than others, try to use simpler store variants
and/or reduce the number of stores.

- Avoid use of complex instructions that require more than 4 uops.



Page 2-55 (106)

Use of the shift and rotate Instructions

The shift and rotate instructions have a longer latency on the Pentium 4 processor
than on previous processor generations. The latency of a sequence of adds will be
shorter for left shifts of three or less. Fixed and variable shifts have the same latency.
Assembly/Compiler Coding Rule 42. (M impact, M generality) If a shift is on a critical
path, replace it by a sequence of up to three adds. If its latency is not critical, use the shift
instead because it produces fewer uops.
The rotate by immediate and rotate by register instructions are more expensive than
a shift. The rotate by 1 instruction has the same latency as a shift.
Assembly/Compiler Coding Rule 43. (ML impact, L generality) Avoid rotate by register
or rotate by immediate instructions. If possible, replace with a rotate by 1 instruction.


Вывод делаю - всякие сдвиги - очень дорого.

> Неправда. И вывод неверный. В FPU можно эмулировать
> целочисленное
> сложение, умножение и деление если режим его работы
> округление к нулю.
> Но как насчет сдвигов? А ротейтов? Не выйдет. Сразу же -
> делать одни

> операции в FPU потом скидывать в память потом читать в
> целочисленный регистр делать сдвиг и абратно в FPU слишком
> дорого. Лучше эмуляция
> через пару 32битных числа.

Со сдвигом согласен, если его только не осуществлять через сложение умножение. А для других операций - тут пардон. Кроме того, целочисленные операции имеют свои коды FIADD, FIDIV, etc. Используя их не надо переводить процессор в режим округления специальной командой.

> Для пущей честности, левый сдвиг на k бит можно эмулировать
> умножением на 2^k в вещественной арифметике, правый сдиг на
> k - умножением на 2^(-k) с последущим конвертацией

Это вещи известные, только вот операции умножения очень дорогие.

> результата к целому с округлением к нулю (truncate).
> Соответственно, rotate можно эмулировать 2 предыдущими
> командами и сложением их результата. Операции с парой
> 32битных чисел все равно гораздно быстрей.
>
Согласен.

>
> И по чей-то злостной воле упорно блуждают абсурднейшие
> слухи о том, что в P4 нет аппаратной инструкции rotate.
> Хоть отдельный FAQ пиши на эту тему. ;-(( Есть она!
> ЕСТЬ!!!!!!!.

Дык, никто и не спорит, только сильно глюкавая она:

Page C-6 (356)

Table C-1 Streaming SIMD Extension 2 128-bit Integer Instructions (continued)


Instruction Latency1 Throughput Execution Unit

PSLLDQ xmm, imm8 4 2 MMX_SHFT
PSLLW/PSLLD/PSLLQ xmm, xmm/imm8 2 2 MMX_SHFT
PSRAW/PSRAD xmm, xmm/imm8 2 2 MMX_SHFT
PSRLDQ xmm, imm8 4 2 MMX_SHFT
PSRLW/PSRLD/PSRLQ xmm, 2 2 MMX_SHFT



Page C-15 (366)


Latency and Throughput with Memory Operands

Typically, instructions with a memory address as the source operand, add one more
µop to the reg, reg instructions type listed in Table C-1 through C-7. However, the
throughput in most cases remains the same because the load operation utilizes port 2
without affecting port 0 or port 1.
Many IA-32 instructions accept a memory address as either the source operand or as
the destination operand. The former is commonly referred to as a load operation, while
the latter a store operation.
The latency for IA-32 instructions that perform either a load or a store operation are
typically longer than the latency of corresponding register-to-register type of the IA-32
instructions. This is because load or store operations require access to the cache
hierarchy and, in some cases, the memory sub-system.
Intel Pentium 4 and Intel Xeon Processor Optimization IA-32 Instruction Latency and Throughput C
For the sake of simplicity, all data being requested is assumed to reside in the first level
data cache (cache hit). In general, IA-32 instructions with load operations that execute
in the integer ALU units require two more clock cycles than the corresponding
register-to-register flavor of the same instruction. Throughput of these instructions
with load operation remains the same with the register-to-register flavor of the
instructions.
Floating-point, MMX technology, Streaming SIMD Extensions and Streaming SIMD
Extension 2 instructions with load operations require 6 more clocks in latency than the
register-only version of the instructions, but throughput remains the same.
When store operations are on the critical path, their results can generally be forwarded
to a dependent load in as few as zero cycles. Thus, the latency to complete and store
isn't relevant here.

Если посмотреть мой первый пост, то там ссылочка на днет - про тоже и говорит - 4 такта ожидания дополнительно. А сам Интел советует заменять сдвиги влево на 1 на сложение. И еще - посмотри, что происходит, если операнд в памяти, а не на регистре - еще 6 тактов. Правда, тут надо считать, что быстрее Load/Shift.Save или Shift в памяти. Но тут для RC5 выбор практически предопределен.

Вопрос - а что будет быстрее после этого - использование команды сдвига или эммуляцие ее?


>
> повезет.
> Что же касается ПодЛинукса, то все равно GCC не обеспечит
> нужной производительности и надо будет писать на ASM'e. До
> сих пор я не видел у АМД толкового мануала о том, как
> что-либо оптимизировать под их процы.

Здесь я не про то, что нет оптимизированного компайлера, а про то, что ты сказал, что этого в принципе нет. А с отсутствием оптимизирующего компилятора я и не спорю. Но наличие хоть какого-то IDE (если gcc/gdb можно так назвать) дает возможность написать всю обслугу на С, а само ядро на ассемблере. На мой взгляд, текущий клиент для большинства платформ так и написан.

> Он есть, но в нем написаны вещи типа - делай такую
> макро-операцию так-то, проц знает эту последовательность
> машинных команд и выполнит ее быстро. А насчет
> универсальных приемов с упором на архитектуру - НЕТ.
> Если я делаю какие-то нестандартные операции, отличные от
> перевода целого числа в вещественное или подсчет количества
> ненулевых битов регистре, то я остаюсь в полном безвестном
> творческом пPолете.


А тут, увы, возразить нечего.

PS Я не слишком напрягаю народ, когда цитирую на английском языке в таком количестве? Если что, то пинайте, я обещаю исправиться.
<dnet> Поиск 






Rambler's Top100
Рейтинг@Mail.ru


  Copyright © 2001-2024 Dmitry Leonov   Page build time: 0 s   Design: Vadim Derkach