Главная » Просмотр файлов » Donald E. Thomas - The Verilog Hardware Description Language, Fifth Edition

Donald E. Thomas - The Verilog Hardware Description Language, Fifth Edition (798541), страница 21

Файл №798541 Donald E. Thomas - The Verilog Hardware Description Language, Fifth Edition (Donald E. Thomas - The Verilog Hardware Description Language, Fifth Edition) 21 страницаDonald E. Thomas - The Verilog Hardware Description Language, Fifth Edition (798541) страница 212019-09-20СтудИзба
Просмтор этого файла доступен только зарегистрированным пользователям. Но у нас супер быстрая регистрация: достаточно только электронной почты!

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

Six times, the loworder bit of the multiplier (mpy) is checked. If it is one, then the multiplicand (mcnd)is concatenated (using the “{ , }” operator) with six bits of zeros on its right and addedto the product (prod). The product and multiplier are both shifted right one place andthe loop continues.The general forms of a concatenation are shown below:concatenation{ expression {, expression} }multiple_ concatenation{ constant_expression concatenation }The first form is that shown in the example. The second allows for the concatenationin the inner braces to be repeated n times where n is given by the constant expression.The input, output, and inout names declared in tasks (and as we will later see,functions) are local variables separate from the variables named at the calling site.Their scope is the task-endtask block.

When a task is called, the internal variablesThe Verilog Hardware Description Language96declared as inputs or inouts receive copies of the values named at the calling site. Thetask proceeds executing. When it is done, then all of the variables declared as inoutsor outputs are copied back to the variables listed at the call site. When copying valuesto and from the call site, the variables at the call site are lined up left-to-right withorder of the input, output, and inout declarations at the task definition site.A task may call itself, or be called from tasks that it has called. Unless the task isdeclared to be automatic, there is only one set of registers to hold the task variables.Thus, the registers used after the second call to the task are the same physical entitiesas those in the previous call(s).

The simulator maintains the thread of control so thatthe returns from a task called multiple times are handled correctly. Further, a task maybe called from separate processes (i.e., always and initial statements) and the task mayeven be stopped at an event control when the task is enabled from another process.There is still only one set of variables for the two invocations of the task to use.

However, the simulator does keep track of the control tokens so that the appropriate returnto the calling process is made when the task exits.When a task is declared automatic, the task is re-entrant. That is, there may becalls to it from several concurrent processes. Indeed, since tasks may have timing andevent controls, several processes may be waiting in the task. Each call to the task,whether from concurrent processes or from itself, works with its own copies of theinternally declared storage. Upon exit from the task, this storage is released and thusin unavailable to any other scope.

Thus inputs, outputs, and other internal variablescannot be assigned values using non-blocking assignments, or traced withstatements, for instance. The point is that non-automatic tasks have static storageallocation. Automatic tasks have dynamic storage allocation which only exists duringa particular instance’s execution.The general form of a task call is:task_enablehierarchical_task_identifier [ (expression {, expression } ) ];It is useful to comment on the concatenation operation in the example. The “{ , }”characters are used to express concatenation of values. In this example, we concatenate two 6-bit values together to add to the 13-bit prod.

mcnd has 6 binary zeros(expressed here in binary format) concatenated onto its right-hand side. Notice thatin this case, an exact bit width must be specified for the constant so that mcnd isproperly aligned with prod for the add.References: functions 3.5.2; Identifiers B.5, G.10Behavioral Modeling973.5.2 FunctionsA Verilog function is similar to a software function.

It is called from within an expression and the value it returns will be used in the expression. The function has one output (the function name) and at least one input. Other identifiers may be declaredwithin the function and their scope will be the function. Unlike a task, a function maynot include delay(#) or event control (@), or wait statements.

Although not illustratedhere, a function may be called from within a continuous assignment. Functions maycall other functions (including itself) but not other tasks. During the execution of thefunction, a value must be assigned to the function name; this is the value returned bythe function.Example 3.10 shows module mark1Fun specified with a multiply function.

Thefunction is defined within a module using the Junction and endfunction keywords. Thefunction declaration includes the function name and bit width. At calling time, theparameters are copied into the function’s inputs; as with tasks, the declaration order isstrictly adhered to. The function executes, making assignments to the function’sname. On return, the final value of the function’s name (multiply) is passed back tothe calling site and, in this example, copied into register acc.

Note that named beginend blocks are used illustrating that new register definitions may be made withinthem. The general form of a function declaration is:function_declarationfunction [automatic] [signed] [range_or_type] function _identifier;function_item_declaration {function_item_declaration}statementendfunction|function [automatic] [signed] [range_or_type]function _identifier (function_port_list);block_item_declaration {block_item_declaration}function_statementendfunction|range_or_typerange | integer | real | realtime | timerange[ msb_constant_expression : lsb _constant_expression ]function_item_declarationblock_item_declaration|tf_input_declaration;tf_input_declarationinput [reg] [signed] [range] list_or_port_identifiers|input [task_port_type] list_or_port_identifiers|The Verilog Hardware Description Language98module mark1Fun;reg[15:0] signedreg [12:0]signedreg [12:0]signedregm [0:8191];pc;acc;ck;//signed 8192 x 16 bit memory// signed 13 bit program counter// signed 13 bit accumulator// a clock signalalwaysbegin: executeInstructionsreg [15:0]ir; // 16 bit instruction register@(posedge ck)ir <= m [pc];@(posedge ck)case (ir [15:13])//case expressions, as before3'b111: acc <= multiply(acc, m [ir [12:0]]);endcasepc <= pc + 1;endfunction signed [12:0] multiply(inputsigned [12:0] a,inputsigned [15:0] b);begin: serialMultreg[5:0]mcnd,mpy;mpy = b[5:0];mcnd = a[5:0];multiply = 0;repeat (6)beginif (mpy[0])multiply = multiply + {mcnd, 6'b000000};multiply = multiply >> 1;mpy = mpy >> 1;endendendfunctionendmoduleExample 3.10 A Function SpecificationBehavioral Modeling99A function is called from inside a procedural expression or from inside a continuousassignment where the call takes the form:function_callhierarchical_function_identifier ( expression {, expression})A function that is not declared automatic has static storage; recursive calls of thefunction will use the same storage.

Of course, this is the hardware view of functions.A function may be declared automatic in which case each call to the function createsdynamic storage for the function instance. This dynamic storage cannot be hierarchically accessed or traced withA special case of a function is the constant function. There is no keyword to declarethem constant. Rather, their inputs are constants or parameterized values that havebeen previously declared. These functions are useful for calculating bitwidths in declarations as illustrated in Example 3.11 of a parameterized memory for the Marklexamples. Here the parameters are Width and number of words (NumWords). Fromthe parameter NumWords, the size of the address port of the memory is calculatedusing the constant function clog2b.module RAM#(parameterWidth =16,NumWords =8192)(inout [Width-l:0]data,input [clog2b(NumWords):0] address,inputrw, ck);reg [Width-l:0]m [0:NumWords-l];function integer clog2b// constant function(input integer size);// assumes non-zero sizebeginfor (clogb2 = -1; size > 0; clogb2 = clogb2 + 1)size = size >> 1;endendfunctionalways…endmodule// internal behavior of the RAMExample 3.11 A Constant Log Base 2 FunctionReferences: functions in continuous assignment 6.3.1; tasks 3.5.1; Identifier B.5, G.10100The Verilog Hardware Description Language3.5.3 A Structural ViewThe task and function examples of the previous sections have illustrated differentorganizations of a behavioral model.

That is, we can choose to model the behavior indifferent ways with the same result. When we used the * operator, we were probablyonly interested in simulation of the model. There are many ways to implement a multiply in hardware, but early in the design process we were content to let the simulatorsubstitute its method.As the design progresses, we want to specify the multiply algorithm that we wantour hardware to implement. This we did by using the task and function statements inthe above examples.

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

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

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

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