p4 spec v1.1 (1185620), страница 4

Файл №1185620 p4 spec v1.1 (Домашнее задание) 4 страницаp4 spec v1.1 (1185620) страница 42020-08-25СтудИзба
Просмтор этого файла доступен только зарегистрированным пользователям. Но у нас супер быстрая регистрация: достаточно только электронной почты!

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

In consequence,a C program fragment such as:if (x) ...(for x an integer base type) must be written in P4 as:if (x != 0) ...(see also the discussion on infinite-precision types and implicit casts 2.6.2 for how the0 in this expression is evaluated).2We propose replacing the keyword and with the equivalent C operator && in a future P4 revision.We propose replacing the keyword or with the equivalent C operator || in a future P4 revision.4We propose replacing the keyword not with the equivalent C operator ! in a future P4 revision.3172.5 Base type operations2 STRUCTURE OF THE P4 LANGUAGE2.5.2 Operations on unsigned fixed-width integersThis section discusses all operations that can be performed on values with bit<W > types.Operations “wrap-around”, similar to C operations on unsigned values (i.e., representing a large value on W bits will only keep the least-significant W bits of the value).

Thereare no arithmetic exceptions; the runtime result of an arithmetic operation is definedfor all combinations of input arguments.All binary operations (except shifts) require both operands to have the same exact typeand width; supplying operands with different widths produces a compile-time error. Noimplicit casts are inserted by the compiler to equalize the widths. There are no binaryoperations that combine signed and unsigned values (except shifts).Table 5 shows all operations available on unsigned values.There is no unsigned integer division operator.2.5.3 Operations on signed fixed-width integersThis section discusses all operations that can be performed on int<W > types.

An int<W >type is a signed integer with W bits represented using 2’s complement.“Underflow” or “overflow” produced by arithmetic cannot be detected: operations “wraparound”, similar to C operations on unsigned values (i.e., representing a large value on Wbits will only keep the least-significant W bits of the value)5 .

There are no arithmetic exceptions; the runtime result of an arithmetic operation is defined for all combinationsof input arguments.All binary operations (except shifts) require both operands to have the same exact type(signedness) and width; supplying operands with different widths or signedness produces a compile-time error. No implicit casts are inserted by the compiler to equalizethe widths. there are no binary operations that combine signed and unsigned values(except shifts).Table 6 shows all operations available on signed values. Note that bitwise operationsare well-defined, since the representation is mandated to be 2’s complement.

There isno signed integer division operator.5Note that C does not define the result of operations that overflow when computing on signed values,whereas P4 does.182.5 Base type operationsOperation==, !=<, >, <=, >=&, |, ^˜<<, >>+ (unary)- (unary)+ (binary)- (binary)*2 STRUCTURE OF THE P4 LANGUAGEDescriptionTest for equality/inequality.

Both operands must have the samewidth. The result is a Boolean value.Unsigned comparisons. Both operands must have the same width.The result is a Boolean value.Bitwise operations; both operands must have the same width; resultis unsigned and has the same width.Result is unsigned and has the same width as the input. Bitwise complement.Left operand is unsigned, right operand must be either an unsignednumber or a non-negative constant integer. The result has the sametype as the left operand. These perform logical shifts (fill with zero.)Shifts with an amount greater or equal to the width of the input produce a result with all bits zero.Unary plus sign; behaves as a no-op.Unary negation; the result is computed by by subtracting its valuefrom 2W . The result is always unsigned and it has the same width asthe input.

The semantics is the same as the C negation of unsignednumbers.Binary addition; associative. Both operands must have the same type;result has the same type. Result is computed by truncating the resultof the mathematical addition to the width of the output (similar to C).Binary subtraction; associative. Both operands must have the sametype; result is unsigned, and has the same type. Result is computedby adding the negation of the second operand (similar to C).Binary unsigned multiplication; associative. Both inputs must havethe same width; result has the same width as the inputs, and is unsigned.

P4 targets may impose additional restrictions (e.g., may require one of the operands to be a compile-time constant value, oronly allow multiplications with powers of two).Table 5: Operations on unsigned values.2.5.4 A note about shiftsShifts (on signed and unsigned values) deserve a special discussion for the followingreasons:• As in C, right shift behaves differently for signed and unsigned values: right shiftfor signed values is an arithmetic shift.• Shifting with a negative amount does not have a clear semantics: while in C theresult is undefined, in P4 the type system makes it illegal to shift with a negative192.5 Base type operationsOperation==, !=<, >, <=, >=&, |, ^˜<<, >>+ (unary)- (unary)+ (binary)- (binary)*2 STRUCTURE OF THE P4 LANGUAGEDescriptionTest for equality/inequality.

Both operands must have the samewidth. The result is a Boolean value.Signed comparisons. Both operands must have the same width. Theresult is a Boolean value.Bitwise operations; both operands must have the same width; resultis signed and has the same width.Result is signed and has the same width as the input. Bitwise complement.Left operand is signed, right operand must be either an unsignednumber or a non-negative constant integer. The result has the sametype as the left operand.

These perform arithmetic shifts. Shifts withan amount greater or equal to the width of the input are allowed.Unary plus sign; behaves as a no-op.Unary negation; the result is signed and it has the same width as theinput.Binary addition; associative. Both operands must have the same type;result has the same type.Binary subtraction; associative. Both operands must have the sametype; result is signed, and has the same type.Binary signed multiplication; associative. Both inputs must have thesame width; result has the same width as the inputs, and is signed.P4 targets may impose additional restrictions (e.g., may require oneof the operands to be a compile-time constant value, or only allowmultiplications with powers of two).Table 6: Operations on signed values.amount.• In C, shifting with an amount larger or equal to the number of bits has an undefined result (unlike our definition).• Finally, shifting may require doing work which is exponential in the number ofbits of the right-hand-side operand.

Consider the following examples:bit<8> x;bit<16> y;... y << x ...... y << 1024 ...Unlike C, P4 gives a precise meaning shifting with an amount larger than the sizeof the shifted value.202.5 Base type operations2 STRUCTURE OF THE P4 LANGUAGEDue to these reasons, P4 targets may impose additional restrictions to shift operations:• Targets may reject shifts by non-constant amounts.• Targets may reject shifts with large non-constant amounts. For example, a targetmay forbid shifting an 8-bit value by a value wider than 3 bits.2.5.5 varbit operationsThe type varbit<W > denotes variable-size bitstrings with a maximum static width of Wbits. Such a bit-string has a dynamic width, which must be smaller or equal than W .Prior to initialization a varbit has a dynamic width of 0.

Varbits support the followingoperation:• Parser extraction into a varbit. This operation sets the dynamic width of the value.The extracted value must be shorter than the static width W .There are no arithmetic, comparisons, bit-wise, or bit extraction operators on varbits.If these are desired, varbit types should not be used.2.5.6 Operations on arbitrary-precision integersThe type int denotes integer values on which computations are performed with arbitrary precision. Table 7 shows all operations that are defined for int values. The onlyvalues that can have the type int are compile-time constants.All the operands that participate in an operation must have type int; binary operations(except shift) cannot combine int values with fixed-width types.

For such expressionsthe compiler will always insert an implicit cast; this cast will always convert the intvalue to the fixed-width type.All computations on int values are carried without information loss. For example, multiplying two 1024-bit values may produce a 2048-bit value (note that concrete representation of int values is not specified).

Casting an int value to a fixed-width type willpreserve the least-significant bits. If the truncation causes significant bits to be lost, thecompiler should emit a suitable warning.Note: bitwise-operations (|, &, ^, ˜) are not defined for int values.

Division and moduloare illegal for negative values (the C language does not give a clear semantics to divisionof signed integers when values are negative).212.6 CastsOperation==, !=<, >, <=, >=<<, >>+ (unary)- (unary)+ (binary)- (binary)*/, %2 STRUCTURE OF THE P4 LANGUAGEDescriptionTest for equality/inequality. Both operands must be ints. The resultis a Boolean value.Signed comparisons. Both operands must be ints. The result is aBoolean value.Right operand must be a positive int. The result has the same typeas the left operand. a << b is a × 2b . a » b is ba/2b c (expressed usingreal-number division).Unary plus sign; behaves as a no-op.Unary negation; the result is an int; no information is lost in negation.Binary addition; associative.

Both operands must be int; result is int,and no information is lost in addition (no overflow).Binary subtraction; associative. Both operands must be int; result isint; no information is lost in subtraction (no overflow).Binary signed multiplication; associative. Both inputs must be int;result is int.

No overflow occurs.Binary signed division and modulo. Both inputs must be positive intvalues; result is a positive int value.Table 7: Operations on arbitrary-precision constant integers.2.6 Casts2.6.1 Explicit castsP4 supports a very limited range of casts. Most casts must be explicit. Most binaryoperations require both operands to have the exact same type. Some type conversionsmay require multiple chained casts. While more onerous for the user, this approach hasseveral benefits:• Makes user intent unambiguous.• Makes the conversion cost explicit.

Some casts involve sign-extensions, and thusrequire significant computational resources.• Reduces the number of cases that have to be considered in the P4 specification.A cast expression is written as in C, (typeRef)exp, where typeRef is a reference to a type(e.g., a type name).All legal casts are shown in table 8.222.6 CastsFrom2 STRUCTURE OF THE P4 LANGUAGETobit<1>boolboolbit<1>bit<W >int<W >int<W >bit<W >bit<W >bit<W1>int<W >int<W1>intbit<W>intint<W>Description0 is false, 1 is truereverse of the abovePreserves all bits unchangedPreserves all bits unchangedif W ≥ W1 this keeps least-significant W1 bits, if W < W1 this causes extension with zero bitsif W ≥ W1 this keeps least-significant W1 bits, if W < W1 this causes extension with the sign bitsRepresents the integer value using two’s complement on a largeenough number of bits and keeps the least-significant W bits; overflowshould lead to a warning, including conversion of a negative numberRepresents the integer value using two’s complement on a largeenough number of bits and keeps the least-significant W bits; overflow should lead to a warningTable 8: Legal P4 casts.2.6.2 Implicit castsUnlike C, P4 allows a very limited number of implicit casts.

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

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

Список файлов курсовой работы

Домашнее задание
VasilenkoAE_521 (switch openflow start)
staticNAT
p4factory
mininet
lvk_demo.py
targets
lvk_task
openflow_mapping
l2.py
l2.pyc
mapping_common.py
mapping_common.pyc
p4src
includes
headers.p4
parser.p4
lvk_task.p4
targets
libpd_thrift
libtbl_packing
tests
pd_thrift
conn_mgr_pd_rpc
__init__.py
__init__.pyc
conn_mgr-remote.
conn_mgr.py
conn_mgr.pyc
constants.py
ttypes.py
ttypes.pyc
devport_mgr_pd_rpc
Свежие статьи
Популярно сейчас
Как Вы думаете, сколько людей до Вас делали точно такое же задание? 99% студентов выполняют точно такие же задания, как и их предшественники год назад. Найдите нужный учебный материал на СтудИзбе!
Ответы на популярные вопросы
Да! Наши авторы собирают и выкладывают те работы, которые сдаются в Вашем учебном заведении ежегодно и уже проверены преподавателями.
Да! У нас любой человек может выложить любую учебную работу и зарабатывать на её продажах! Но каждый учебный материал публикуется только после тщательной проверки администрацией.
Вернём деньги! А если быть более точными, то автору даётся немного времени на исправление, а если не исправит или выйдет время, то вернём деньги в полном объёме!
Да! На равне с готовыми студенческими работами у нас продаются услуги. Цены на услуги видны сразу, то есть Вам нужно только указать параметры и сразу можно оплачивать.
Отзывы студентов
Ставлю 10/10
Все нравится, очень удобный сайт, помогает в учебе. Кроме этого, можно заработать самому, выставляя готовые учебные материалы на продажу здесь. Рейтинги и отзывы на преподавателей очень помогают сориентироваться в начале нового семестра. Спасибо за такую функцию. Ставлю максимальную оценку.
Лучшая платформа для успешной сдачи сессии
Познакомился со СтудИзбой благодаря своему другу, очень нравится интерфейс, количество доступных файлов, цена, в общем, все прекрасно. Даже сам продаю какие-то свои работы.
Студизба ван лав ❤
Очень офигенный сайт для студентов. Много полезных учебных материалов. Пользуюсь студизбой с октября 2021 года. Серьёзных нареканий нет. Хотелось бы, что бы ввели подписочную модель и сделали материалы дешевле 300 рублей в рамках подписки бесплатными.
Отличный сайт
Лично меня всё устраивает - и покупка, и продажа; и цены, и возможность предпросмотра куска файла, и обилие бесплатных файлов (в подборках по авторам, читай, ВУЗам и факультетам). Есть определённые баги, но всё решаемо, да и администраторы реагируют в течение суток.
Маленький отзыв о большом помощнике!
Студизба спасает в те моменты, когда сроки горят, а работ накопилось достаточно. Довольно удобный сайт с простой навигацией и огромным количеством материалов.
Студ. Изба как крупнейший сборник работ для студентов
Тут дофига бывает всего полезного. Печально, что бывают предметы по которым даже одного бесплатного решения нет, но это скорее вопрос к студентам. В остальном всё здорово.
Спасательный островок
Если уже не успеваешь разобраться или застрял на каком-то задание поможет тебе быстро и недорого решить твою проблему.
Всё и так отлично
Всё очень удобно. Особенно круто, что есть система бонусов и можно выводить остатки денег. Очень много качественных бесплатных файлов.
Отзыв о системе "Студизба"
Отличная платформа для распространения работ, востребованных студентами. Хорошо налаженная и качественная работа сайта, огромная база заданий и аудитория.
Отличный помощник
Отличный сайт с кучей полезных файлов, позволяющий найти много методичек / учебников / отзывов о вузах и преподователях.
Отлично помогает студентам в любой момент для решения трудных и незамедлительных задач
Хотелось бы больше конкретной информации о преподавателях. А так в принципе хороший сайт, всегда им пользуюсь и ни разу не было желания прекратить. Хороший сайт для помощи студентам, удобный и приятный интерфейс. Из недостатков можно выделить только отсутствия небольшого количества файлов.
Спасибо за шикарный сайт
Великолепный сайт на котором студент за не большие деньги может найти помощь с дз, проектами курсовыми, лабораторными, а также узнать отзывы на преподавателей и бесплатно скачать пособия.
Популярные преподаватели
Добавляйте материалы
и зарабатывайте!
Продажи идут автоматически
6510
Авторов
на СтудИзбе
302
Средний доход
с одного платного файла
Обучение Подробнее