vhdl multiplicationof 2 numbers - vhdl

I am a new at vhdl and i have to multiplication two unsigned vectors like we all did in high scool
so i wrote the program and it dose compile but the result is not good.
The logic looks ok but still it dose not work can any one help.
I could not get how to place code here so please see the image attached.
Thx

When writing VHDL you'll first and foremost need to think hardware. Even though various statements may look similar to what you know from other languages, many of these behave differently, as they are mapped to hardware and evaluated in parallel rather than sequentially.
For instance, for loops in VHDL do not iterate through the loop, but rather replicate the loop contents and evaluate all of these in parallel. So your idea of accumulating temp will not work, as all values of temp1 would be available at the same time instead of one after another.
The easy way of handling multiplication is to just use the * operator, as many synthesizers will pick this up and automatically instantiate the necessary hardware. I assume this is some form of exercise though, where you need to implement the functionality yourself - so just ditch the for loop and store the intermediate results in their own variable, and then add them all up in the end.

Related

How can I write a large VHDL module and keep it readable?

I'm trying to write the control logic module for a toy processor. It cycles through the fetch/decode/execute states, reads and writes from various bits of memory, and sets a bunch of control signals. It's somewhat large, and as far as I can tell it can't really be subdivided into smaller modules.
I don't want to put the logic for all of the states into one process -- it's hard to read, and the mass of intermediate aliases & signals are a pain when using the simulator.
I tried splitting each state's logic into its own process, but then I had problems with multiple drivers.
I also tried declaring separate procedures for each state's logic in the head of one main process, and had the process just call the correct procedure based on the current state. This worked quite nicely, with modular "functions" and a more readable structure... but each procedure's intermediate signals aren't visible in the simulator (and maybe not accessible to a testbench? I gave up before trying that.). I was using ISim in case that's relevant.
Was I doing something wrong? Is there some trick I can use to avoid having one massive monolithic process?
EDIT: code for the module is here.
It could just be that you need to use an editor better suited to reading large VHDL files. I regularly work with 3000+ line VHDL files where most of the space is the logic of a single process, and have no difficulties reading them due to an editor that supports code folding.
I use Notepad++, but I'm sure there are other editors that can support folding on VHDL syntax. When I open a file, I press alt+0 to fold every possible syntax folding point then expand as needed to the part I'm working on. You can also use line hiding to fold arbitrary sections of your file, although that's a little more awkward to work with.
If you have large groups of related concurrent statements you can easily group them into a folding point with a name : if true generate which also allows you to declare intermediate signals outside of the scope of your main architecture (block statements work, but aren't supported by all tools). To force a folding point within a process I use if true then.
If you are designing a processor that implements the different operations in a giant case statement, then what you are really describing is a series of parallel functional units, feeding an output multiplexer. You might have an output that is driven, depending on the op mode, by the output of either a multiplication, addition, subtraction, some logic operation, a shift, etc.
You can easily design this in a modular way, by implementing each functional unit in its own entity, some of which might be quite simple. In the first instance, these blocks would operate unconditionally, and their outputs would feed an output multiplexer. You might later add enable signals, driven by your instruction decoding logic, that enable only the blocks that will be used in a particular operation, in order to save power. It might sound like you will end up with a lot of control signals using this approach, but if you put them all in a record, it makes the code quite compact, while at the same time allowing verbosity and readability at the point where a control signal is used, for example:
AddSub : entity work.AdderSubtractor
port map (
clk => clk,
enable => decoded_instruction.addsub_enable,
a => a,
b => b,
mode => decoded_instruction.addsub_mode, -- This might be an enumerated type
output => addsub_output
);
There would be other _output signals, and at the end you would have something like
OutputMux : process (all)
begin
case decoded_instruction.output_mux_select is
when ADD_SUB => output <= addsub_output;
when MULT => output <= mult_output;
when LOGIC => output <= logic_output;
end case;
end process;
One bonus of doing it this way is that you might find it efficient for several of the functions to be implemented in a DSP block in the FPGA; you can easily design a functional block for add, subtract, multiply, written to target the DSP block in your device. The output of this would be just another input to your 'output' multiplexer. In my experience you should be able to efficiently implement many of your processing functions using a single DSP block (or a single entity that describes a few cascaded DSP blocks, depending on your data path width).
Personally I much prefer this approach of making the design very modular. In a recent multicore DSP project, I have only a couple of files that have ~500 lines, with the majority having 200 or less. This means that when I come back to a part of the design, it usually fits on one page, and can easily be picked up and understood in a very short amount of time. I also find that when implementing heavy pipelining to improve the performance of the design, having too much going on in one process or entity can make this job an order of magnitude more difficult.
Lastly, if functional elements are contained in small entities, you can more easily simulate, test, and verify just that bit of code in isolation, which in my experience allows the block to be signed off more quickly, while at the same time giving more confidence in the code. If everything is in one process, it is harder to have confidence that making a change that fixes or improves one thing, isn't going to break something else. Again in a heavily pipelined design, I find that it can be quite easy to change something that inadvertently causes the design to fail an aggressive timing constraint, so the simpler the entities, the smaller the chances of this happening.
As said, your question is hard to answer. How many lines are we talking about?
You could look up good VHDL code practises though:
- aliases should be avoided (not all tools even support then AFAIK)
- give signals/variables a clear name
- try to group functionality
- try not to change a signal/variable on 2 places separated by 500lines, usually there is a way
- if really needed you could consider using shared variables, introduced in VHDL93. (this will, however, not solve your multiple driver issue)
- do not forget the availability of records to group signals
About making your "intermediate signals visible", you could write
junk_proc: process(clk, rst) is
variable a,b,c: of_some_types;
begin
if rst then
//do reset stuff
elsif rising_edge(clk)
b:=func1(a);
c:=func2(b);
end if;
end process;
variables a,b and c (plain wires in this case) could obviously be visualized in any simulation tool.
If, however, you write b=func1(func2(func3(func4(a)))), do not forget that you describe all this to happen in a single clock cycle. Considering your description I bet you'll run into problems, but perhaps that's a good way of learning.

Case statement vs If else in VHDL

What is main differences between if else and case statement in VHDL. Although both look similar and sometime replace each other.but What logic circuit appear after synthesis . When should we go for if else or case statement ?
Assuming an if-statement and a case-statement describes the same behavior, then the resulting circuit is likely to be identical after the synthesis tools done the translation and optimization.
As Paebbels writes in the comment, the details are described for each tool in the relevant synthesis guide, and there are probably tool-dependent cases where the result may differ, but as a general working assumption, then the synthesis tool will get to the same circuit for equivalent if-statements and case-statements.
The critical point is usually to make correct and maintainable VHDL code, and here readability counts, so choose an if-statement or a case-statement depending on what makes the code most straight forward, and don't try to control the resulting circuit through VHDL constructions, unless there is a specific reason that this is required.
Note that in the if-statement early conditions takes priority over later, but in the case-statement all when have equal priority.
Remember that VHDL is parallel programming language and a form of declarative programming see here as opposed to procedural programming like c/c++ and another other sequential language.
This means in essence, you are telling or attempting to describe to the compiler with your code what the behavior should be, and not specifically telling it what to do or what the behavior is like with procedural programming. This might be what prompted you to ask the question.
Now remember however, that the sequencing of the if or case will affect synthesis. With FPGA's nowadays, all combinatorial part of the logic are in the form of Loop up tables which are internally designed as cascaded arrays multiplexers grouped together to form LUTs with input number N commonly 4 See here for more details, and the compiler decides how to configure these arrays of LUTs.
The ordering can affect the number of cascaded multiplexer that the compiler calculates before the output is resolved.
Note that although in theory, it is possible to get the same behaviour for both if and switch. Case is looking at a single variable and deciding cases for each possible outcome while an If statement can be applied to multiple variables at the same time.
So flexibility? I would say goes to If. However with great power comes great responsibility, if is easy it use several signals from everywhere and if not done properly can lead to bad design, ie coupling of too many variable and any change is subject to failure due to too many dependency issues. Case is suitable for state machines but that is also true for procedural languages I suppose.
In addition, if you use too many different signals to act as conditions to your If, it can affect timing. which may mean limitation in your clock frequency, if you are working with high speed and the list goes on. clock skew, need to constrain signals etc.

When would you swap two numbers without using a third variable?

I have read several sources that discuss how to swap two numbers without using a third variable. These are a few of the most relevant:
How do you swap two integer variables without using any if conditions, casting, or additional variables?
Potential Problem in "Swapping values of two variables without using a third variable"
Swap two integers without using a third variable
http://www.geeksforgeeks.org/swap-two-numbers-without-using-temporary-variable/
I understand why it doesn't make sense to use the described methods in most cases: the code becomes cluttered and difficult to read and will usually execute more slowly than a solution utilizing a third "temp" variable. However, none of the questions I have found discuss any benefits of the two-variable methods in practice. Do they have any redeeming qualities or benefits(historical or contemporary), or are they only useful as obscure programming trivia?
At this point it's just a neat trick. Speed-wise if it makes sense though your compiler will recognize a normal swap and optimize it appropriately (but no guarantees that it will recognize weird xoring and optimize that appropriately).
Another strike against xor is that if one variable alias the other, xor’ing them will zero both out. Since you’ll have to check for and handle this condition, you’ll have extra code involved – probably by using the third variable method.
You could also try adding and subtracting values… except that you’d have to check for and handle overflow, which would involve more code (probably the third variable method). Multiplication and division have the same flaw, but more importantly, there’s the exquisite delight of representing fractions in binary (so this wouldn’t work in the first place).
Edit: D’oh, sorry for the thread necromancy… got so caught up in following links that I forgot to check the dates.

How do for loops in Verilog execute?

Do for loops in Verilog execute in parallel? I need to call a module several times, but they have to execute at the same time. Instead of writing them out one by one, I was thinking of using a for loop. Will it work the same?
Verilog describes hardware, so it doesn't make sense to think in terms of executing loops or calling modules in this context. If I understand the intent of your question correctly, you'd like to have multiple instantiations of the same module with distinct inputs and outputs.
To accomplish this you can use Verilog's generate statements to generate the instantiations automatically.
You can also use the auto_template functionality in Emacs' excellent verilog-mode. I prefer this approach as each instantiation appears explicitly in my source code and I find it easier to detect errors.
As jlf answered, you're looking for a generate statement. You would use a for-loop to model combinational logic, such as going through all of the bits in a register and computing an output. This would be in an always block or even an initial block in your testbench.

How many lines should a function have at most?

Is there a good coding technique that specifies how many lines a function should have ?
No. Lines of code is a pretty bad metric for just about anything. The exception is perhaps functions that have thousands and thousands of lines - you can be pretty sure those aren't well written.
There are however, good coding techniques that usually result in fewer lines of code per function. Things like DRY (Don't Repeat Yourself) and the Unix-philosophy ("Write programs that do one thing and do it well. Write programs to work together. Write programs to handle text streams, because that is a universal interface." from Wikipedia). In this case replace "programs" with "functions".
I don't think it matters, who is to say that once a functions lengths passes a certain number of lines it breaks a rule.
In general just code clean functions easy to use and reuse.
A function should have a well defined purpose. That is, try to create functions which does a single thing, either by doing the thing itself or by delegating work to a number of other functions.
Most functional compilers are excellent at inlining. Thus there is no inherent price to pay for breaking up your code: The compiler usually does a good job at deciding if a function call should really be one or if it can just inline the code right away.
The size of the function is less relevant though most functions in FP tend to be small, precise and to the point.
There is a McCabe metric of Cyclomatic Complexity which you might read about at this Wikipedia article.
The metric measures how many tests and loops are present in a routine. A rule of thumb might be that under 10 is a manageable amount of complexity while over 11 becomes more fault prone.
I have seen horrendous code that had a Complexity metric above 50. (It was error-prone and difficult to understand or change.) Re-writing it and breaking it down into subroutines reduced the complexity to 8.
Note the Complexity metric is usually proportional to the lines of code. It would provide you a measure on complexity rather than lines of code.
When working in Forth (or playing in Factor) I tend to continually refactor until each function is a single line! In fact, if you browse through the Factor libraries you'll see that the majority of words are one-liners and almost nothing is more than a few lines. In a language with inner-functions and virtually zero cost for calls (that is, threaded code implicitly having no stack frames [only return pointer stack], or with aggressive inlining) there is no good reason not to refractor until each function is tiny.
From my experience a function with a lot of lines of code (more than a few pages) is a nightmare to maintain and test. But having said that I don't think there is a hard and fast rule for this.
I came across some VB.NET code at my previous company that one function of 13 pages, but my record is some VB6 code I have just picked up that is approx 40 pages! Imagine trying to work out which If statement an Else belongs to when they are pages apart on the screen.
The main argument against having functions that are "too long" is that subdividing the function into smaller functions that only do small parts of the entire job improves readability (by giving those small parts actual names, and helping the reader wrap his mind around smaller pieces of behavior, especially when line 1532 can change the value of a variable on line 45).
In a functional programming language, this point is moot:
You can subdivide a function into smaller functions that are defined within the larger function's body, and thus not reducing the length of the original function.
Functions are expected to be pure, so there's no actual risk of line X changing the value read on line Y : the value of the line Y variable can be traced back up the definition list quite easily, even in loops, conditionals or recursive functions.
So, I suspect the answer would be "no one really cares".
I think a long function is a red flag and deserves more scrutiny. If I came across a function that was more than a page or two long during a code review I would look for ways to break it down into smaller functions.
There are exceptions though. A long function that consists of mostly simple assignment statements, say for initialization, is probably best left intact.
My (admittedly crude) guideline is a screenful of code. I have seen code with functions going on for pages. This is emetic, to be charitable. Functions should have a single, focused purpose. If you area trying to do something complex, have a "captain" function call helpers.
Good modularization makes friends and influences people.
IMHO, the goal should be to minimize the amount of code that a programmer would have to analyze simultaneously to make sense of a program. In general, excessively-long methods will make code harder to digest because programmers will have to look at much of their code at once.
On the other hand, subdividing methods into smaller pieces will only be helpful if those smaller pieces can be analyzed separately from the code which calls them. Splitting a method into sub-methods which would only be meaningful in the context where they are called is apt to impair rather than improve legibility. Even if before splitting the method would have been over 250 lines, breaking it into ten pieces which don't make sense in isolation would simply increase the simultaneous-analysis requirement from 250 lines to 300+ (depending upon how many lines are added for method headers, the code that calls them, etc.) When deciding whether a method should be subdivided, it's far more important to consider whether the pieces make sense in isolation, than to consider whether the method is "too long". Some 20-lines routine might benefit from being split into two ten-line routines and a two-line routine that calls them, but some 250-line routines might benefit from being left exactly as they are.
Another point which needs to be considered, btw, is that in some cases the required behavior of a program may not be a good fit with the control structures available in the language it's written in. Most applications have large "don't-care" aspects of their behavior, and it's generally possible to assign behavior that will fit nicely with a language's available control structures, but sometimes behavioral requirements may be impossible to meet without awkward code. In some such cases, confining the awkwardness to a single method which is bloated, but which is structured around the behavioral requirements, may be better than scattering it among many smaller methods which have no clear relationship to the overall behavior.

Resources