precisionrtl style

359
Precision ® Synthesis Style Guide Includes Precision RTL Synthesis, Precision RTL Plus & Precision Hi-Rel Release 2011a Update2 November 2011 © 1995-2011 Mentor Graphics Corporation All rights reserved. This document contains information that is proprietary to Mentor Graphics Corporation. The original recipient of this document may duplicate this document in whole or in part for internal business purposes only, provided that this entire notice appears in all copies. In duplicating any part of this document, the recipient agrees to make every reasonable effort to prevent the unauthorized use and distribution of the proprietary information.

Upload: maharaj-mmaya

Post on 24-Oct-2014

136 views

Category:

Documents


1 download

TRANSCRIPT

Page 1: PrecisionRTL Style

Precision® Synthesis Style GuideIncludes

Precision RTL Synthesis, Precision RTL Plus &Precision Hi-Rel

Release 2011a Update2

November 2011

© 1995-2011 Mentor Graphics CorporationAll rights reserved.

This document contains information that is proprietary to Mentor Graphics Corporation. The original recipient of thisdocument may duplicate this document in whole or in part for internal business purposes only, provided that this entirenotice appears in all copies. In duplicating any part of this document, the recipient agrees to make every reasonableeffort to prevent the unauthorized use and distribution of the proprietary information.

Page 2: PrecisionRTL Style

This document is for information and instruction purposes. Mentor Graphics reserves the right to makechanges in specifications and other information contained in this publication without prior notice, and thereader should, in all cases, consult Mentor Graphics to determine whether any changes have beenmade.

The terms and conditions governing the sale and licensing of Mentor Graphics products are set forth inwritten agreements between Mentor Graphics and its customers. No representation or other affirmationof fact contained in this publication shall be deemed to be a warranty or give rise to any liability of MentorGraphics whatsoever.

MENTOR GRAPHICS MAKES NO WARRANTY OF ANY KIND WITH REGARD TO THIS MATERIALINCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY ANDFITNESS FOR A PARTICULAR PURPOSE.

MENTOR GRAPHICS SHALL NOT BE LIABLE FOR ANY INCIDENTAL, INDIRECT, SPECIAL, ORCONSEQUENTIAL DAMAGES WHATSOEVER (INCLUDING BUT NOT LIMITED TO LOST PROFITS)ARISING OUT OF OR RELATED TO THIS PUBLICATION OR THE INFORMATION CONTAINED IN IT,EVEN IF MENTOR GRAPHICS CORPORATION HAS BEEN ADVISED OF THE POSSIBILITY OFSUCH DAMAGES.

RESTRICTED RIGHTS LEGEND 03/97

U.S. Government Restricted Rights. The SOFTWARE and documentation have been developed entirelyat private expense and are commercial computer software provided with restricted rights. Use,duplication or disclosure by the U.S. Government or a U.S. Government subcontractor is subject to therestrictions set forth in the license agreement provided with the software pursuant to DFARS 227.7202-3(a) or as set forth in subparagraph (c)(1) and (2) of the Commercial Computer Software - RestrictedRights clause at FAR 52.227-19, as applicable.

Contractor/manufacturer is:Mentor Graphics Corporation

8005 S.W. Boeckman Road, Wilsonville, Oregon 97070-7777.Telephone: 503.685.7000

Toll-Free Telephone: 800.592.2210Website: www.mentor.com

SupportNet: supportnet.mentor.com/Send Feedback on Documentation: supportnet.mentor.com/user/feedback_form.cfm

TRADEMARKS: The trademarks, logos and service marks ("Marks") used herein are the property ofMentor Graphics Corporation or other third parties. No one is permitted to use these Marks without theprior written consent of Mentor Graphics or the respective third-party owner. The use herein of a third-party Mark is not an attempt to indicate Mentor Graphics as a source of a product, but is intended toindicate a product from, or associated with, a particular third party. A current list of Mentor Graphics’trademarks may be viewed at: www.mentor.com/terms_conditions/trademarks.cfm.

Page 3: PrecisionRTL Style

Precision Synthesis Style Guide, 2011a Update2 3November 2011

Table of Contents

Chapter 1VHDL Language Features . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15

Entities and Architectures . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16Entity and Package Handling . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17Entity Compiled as the Design Root. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17Configuration . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17Processes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19

Literals . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21Types. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22Enumerated Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23Integer Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23Floating-point Types. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25Physical Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26Syntax and Semantics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26Array Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26Record Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29Subtypes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30Type Conversions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31IEEE 1076 Predefined Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 32IEEE 1164 Predefined Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 32

Objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33Signals. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33Constants. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 34Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 34Ports . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 34Generics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35Loop Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35

Statements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35Conditional Statements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 36Selection Statements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 36Loop Statements and Generate Statements. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 37Assignment Statements. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 39

Operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 41IEEE 1076 Predefined Operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 41IEEE 1164 Predefined Operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 43Operator Overloading . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 44

Attributes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 44VHDL Predefined Attributes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 45Mentor Graphics Predefined Attributes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 45User-Defined Attributes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 45Using Attributes in the Source Code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 46

Blocks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 47

Page 4: PrecisionRTL Style

Table of Contents

4November 2011

Precision Synthesis Style Guide, 2011a Update2

Functions and Procedures . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 48Resolution Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 50

Syntax and Semantics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 50Synthesis Issues . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 51

Component Instantiation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 53Binding a Component . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 55

Option 1 - Using a Default Binding . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 56Option 2 - Using a Configuration Specification . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 56Option 3 - Matching a Component Name to a Library Cell . . . . . . . . . . . . . . . . . . . . . . . . 57Option 4 - Creating a Black Box by Omitting the Entity . . . . . . . . . . . . . . . . . . . . . . . . . . 57Finding Definitions of Components . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 58

Packages. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 59Aliases . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 61Syntax and Semantic Restrictions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 62

Synthesis Tool Restrictions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 62VHDL Language Restrictions. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 63

Chapter 2VHDL 2008 Language Features . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 67

Conditional and Selected Sequential Assignments . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 67Simplified Case Expression Support . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 68Unconstrained Element Support . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 69Context Declarations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 69Extensions to Generate . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 71Fixed Point Package. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 71Expressions Port Map . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 72Read Out Ports . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 72Simplified Sensitivity List . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 73Block Comments . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 73Matching Case Statement . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 74Array-Scalar Operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 74Logical Reduction Operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 75Matching Relational Operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 75Conditional Operator Support . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 75Maximum and Minimum Function Support . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 76Unconstrained Record Elements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 76

Chapter 3Verilog Language Features . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 77

Modules . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 78’macromodule’ . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 78

Numbers. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 79Data Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 80

Net Data Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 81Register Data Type . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 82Parameter Data Type. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 82

Continuous Assignments . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 83Net Declaration Assignment . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 83

Page 5: PrecisionRTL Style

Table of Contents

Precision Synthesis Style Guide, 2011a Update2 5November 2011

Continuous Assignment Statement . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 84Procedural Assignments. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 84Always Blocks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 85Module Instantiation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 87Technology-Specific Macros . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 87

Parameter Override During Instantiation of Module . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 89Defparam Statement . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 89’unconnected_drive’ and ’nounconnected_drive’. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 89

Operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 90Operands . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 90‘signed and ‘unsigned Attributes on Operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 94Operator Precedence . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 94

Statements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 95If-Else Statements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 95Case Statements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 96Case Statement and Multiplexer Generation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 98for Statements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 101Disable Statement . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 102forever, repeat, while and Generalized Form of for Loop . . . . . . . . . . . . . . . . . . . . . . . . . 103

Functions and Tasks. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 103Functions. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 104Tasks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 105Inout Ports in Task . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 105Access of Global Variables from Functions and Tasks . . . . . . . . . . . . . . . . . . . . . . . . . . . 106

System Task Calls . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 106System Function Calls . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 106Initial Statement . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 107

Compiler Directives . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 107Verilog Issues and Limitations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 107

Comparing With X and Z . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 107Variable Indexing of Bit Vectors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 108

Synthesis Directives. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 109parallel_case and full_case directives. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 109translate_off and translate_on directives . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 109attribute directive . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 109Syntax and Semantic Restrictions. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 110

Verilog 2001 Support. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 111Supported Verilog 2001 Constructs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 111Detailed Description . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 112

Chapter 4SystemVerilog Language Features . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 119

SystemVerilog Support in Precision . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 119How Precision Reads SystemVerilog files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 122Compilation Unit Scope Settings. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 123

Altering the Compilation Unit Scope . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 123When Option -all_file_cunit_scope=false (Default in Precision). . . . . . . . . . . . . . . . . . . . 126

Basic Language Constructs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 127

Page 6: PrecisionRTL Style

Table of Contents

6November 2011

Precision Synthesis Style Guide, 2011a Update2

Literal Values . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 128Data Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 130Arrays . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 135Data Declarations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 138Attributes. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 139Operators and Expressions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 139Procedural Statements and Control flow . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 139Processes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 143Tasks and Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 145Hierarchy. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 147Interfaces. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 148Compiler Directives . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 150Unpacked Array Concatenation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 150Foreach Loop Support. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 151Removing Text Substitution Macros . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 151Set Membership Operator (Inside Operator) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 152

Example Designs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 152

Chapter 5Inferring Arithmetic and Relational Operators. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 169

Common Guidelines . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 169VHDL/Verilog Differences . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 169Optimization Issues . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 170

Resource Sharing and Common Subexpression Elimination . . . . . . . . . . . . . . . . . . . . . . . 170Reducing Counter Logic . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 171

Attributes That Affect Operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 172Arithmetic Examples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 172

Up Counter . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 174Up Counter with Enable . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 175Up Counter with Enable and Load . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 176Up Counter with Enable, Load, and Cout. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 177Up Counter with Asynchronous Load and Reset . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 178Down Counter. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 179Bidirectional Counter . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 180BCD Counter . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 181Adder with Carry-In . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 182Adder / Subtractor. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 183Arithmetic Logic Unit. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 184Divide By N . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 187Pipelined Multiplier . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 188

Chapter 6Boolean Logic . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 189

Common Guidelines . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 189VHDL/Verilog Differences . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 189Optimization Issues . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 189

Unintended Combinatorial Loops (Latches). . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 189Using Variables before they are assigned. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 192

Page 7: PrecisionRTL Style

Table of Contents

Precision Synthesis Style Guide, 2011a Update2 7November 2011

Attributes Relating to Boolean Logic . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 192Boolean Examples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 193

Basic Gates . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 194Tri-State . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 195Tri-State Bus . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 196Bi-Directional Bus . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 197Generic Width Decoder . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 198I/O Buffers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 199Seven Segment Decoder . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 200Priority Encoder . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 201Multiplexer . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 202Parallel Mux . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 203Serial Mux. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 204

Chapter 7Registers. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 205

Common Guidelines . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 205Synchronous Sets and Resets . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 205Asynchronous Sets and Resets . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 205Clock Enable. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 206

VHDL / Verilog Differences . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 206Determining the Clock Edge. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 206Asynchronous set and reset. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 207VHDL Wait Statements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 207Predefined Flip-flops and Latches . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 207VHDL Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 207

Optimization Issues . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 208Attributes That Affect Registers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 209Register Examples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 209

D Latch . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 213D Latch with Asynchronous Set and Reset. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 214Generic N-Bit Register with Enable . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 215D Flip Flop . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 216D Flip Flop with Enable . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 217D Flip Flop with Synchronous Reset . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 218D Flip Flop with Asynchronous Reset . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 219D Flip Flop with Synchronous Set . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 220D Flip Flop with Asynchronous Set . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 221D Flip Flop with Enable and Synchronous Reset . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 222D Flip Flop with Enable and Asynchronous Reset. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 223D Flip Flop with Enable and Synchronous Set. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 224D Flip Flop with Enable and Asynchronous Set. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 225D Flip Flop with Synchronous Reset and Set . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 226D Flip Flop with Asynchronous Reset and Set. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 227D Flip Flop with Enable and Synchronous Reset and Set . . . . . . . . . . . . . . . . . . . . . . . . . 228D Flip Flop with Enable and Asynchronous Reset and Set . . . . . . . . . . . . . . . . . . . . . . . . 229D Flip Flop with Asynchronous Reset and Synchronous Set . . . . . . . . . . . . . . . . . . . . . . . 230D Flip Flop with Enable and Asynchronous Reset and Synchronous Set . . . . . . . . . . . . . 231

Page 8: PrecisionRTL Style

Table of Contents

8November 2011

Precision Synthesis Style Guide, 2011a Update2

D Flip Flop with Synchronous Reset and Asynchronous Set . . . . . . . . . . . . . . . . . . . . . . 232D Flip Flop with Enable and Synchronous Reset and Asynchronous Set . . . . . . . . . . . . . 233Gated Clock Conversion-AND. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 234Gated Clock Conversion-NAND . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 235Gated Clock Conversion-OR . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 236Gated Clock Conversion-NOR . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 237Gated Clock Conversion-Cascaded Clocks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 238Right Shifter . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 240Asynchronous Right Shifter . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 241Synchronous Right Shifter . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 242Serial Shifter . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 243Bi-Directional Shifter . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 244Right Logical Shifter. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 245

Chapter 8Memory . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 247

Common Guidelines . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 247Single Port RAMs. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 247Dual Port RAMs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 247Resets for Memories . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 247ROMs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 248General Coding Guidelines for ROM Inference. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 248Smart ROM to RAM Inference and Mapping Algorithms . . . . . . . . . . . . . . . . . . . . . . . . . 248Suggested Coding Techniques for RAM and ROM . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 250Byte-Enable Memories . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 256Supported Byte-Enable Device Families . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 256Inferring Byte-Enabled RAM in Precision . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 256Supported Byte-Enable RTL Coding Styles . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 257

VHDL/Verilog Differences . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 263Initializing RAM in Verilog . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 263

Optimization Issues . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 264Initialization Values . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 264

Attributes Relating to Memory . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 264Memory Coding Examples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 265

Synchronous RAM . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 267RAM with Synchronous Input . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 268RAM with Synchronous Output . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 269RAM with Synchronous Address . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 270RAM with Synchronous Input/Output . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 271Asynchronous RAM . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 272Synchronous I/O RAM . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 273I/O RAM with Synchronous Input . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 274I/O RAM with Synchronous Output . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 275I/O RAM with Synchronous Address . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 276I/O RAM with Synchronous Input/Output . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 277I/O Asynchronous RAM. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 278Dual Port RAM. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 279Resets for Memory . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 280

Page 9: PrecisionRTL Style

Table of Contents

Precision Synthesis Style Guide, 2011a Update2 9November 2011

ROM . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 281Synchronous ROM . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 287

Chapter 9Finite State Machines . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 291

Common Guidelines . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 291Optimization Issues . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 292

Encoding Styles . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 293Specifying the Encoding Style . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 294Attributes Relating to Finite State Machines . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 295FSM Encoding using a Verilog Pragma . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 296Advanced FSM Optimization . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 296

Safe Finite State Machines. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 297How Precision Implements a Safe FSM . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 297

Leonardo/Precision Differences. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 303Coding Examples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 303

Single Process State Machine . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 304Two Process State Machine . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 305Three Process State Machine . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 306Moore State Machine . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 309Mealy State Machine . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 312

Chapter 10DSP Blocks. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 315

Common Guidelines . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 315Basic Requirements for DSP Inference . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 315General Inference Support . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 315Inference and Instantiation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 316Reset Design Requirements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 317Vendor Specific DSP Optimizations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 318

Attributes Relating to DSP Blocks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 319DSP Code Examples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 320

MULT-ADD . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 321MULT-ADDSUB . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 323MULT-ACC . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 325MULT-ACC-ADDSUB . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 327Fully Pipelined 35x18 Multiplier . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 329Instantiating DSP Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 332

Chapter 11Exemplar VHDL Package . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 337

The Exemplar Packages. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 337Predefined Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 338Predefined Attributes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 338Predefined Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 339Predefined Procedures . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 343

Interfacing With Other VHDL Tools. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 345Performing Post-layout Functional Simulation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 345

Page 10: PrecisionRTL Style

Table of Contents

10November 2011

Precision Synthesis Style Guide, 2011a Update2

Working with the Synopsys Package. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 346

Index

End-User License Agreement

Page 11: PrecisionRTL Style

11November 2011

Precision Synthesis Style Guide, 2011a Update2

List of Examples

Example 3-1. Verilog Defparm . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 89Example 4-1. SystemVerilog ALU . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 153Example 4-2. SystemVerilog Counter . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 154Example 4-3. SystemVerilog FSM 1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 156Example 4-4. SystemVerilog FSM 2 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 158Example 4-5. SystemVerilog FSM 3 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 160Example 4-6. SystemVerilog FSM Reencoded . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 163Example 4-7. SystemVerilog Interface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 165Example 6-1. VHDL Bi-Directional Bus. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 197Example 6-2. Verilog Bi-Directional Bus . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 197Example 9-1. VHDL Safe Finite State Machine . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 298Example 9-2. Verilog Safe Finite State Machine with Default Clause . . . . . . . . . . . . . . . . . 300Example 9-3. Verilog Safe Finite State Machine with an unreachable state and without DefaultClause. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 301Example 9-4. VHDL Three Process FSM . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 306Example 9-5. Verilog Three Process FSM . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 307Example 9-6. VHDL Moore State Machine . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 309Example 9-7. Verilog Moore State Machine . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 310Example 9-8. VHDL Mealy State Machine. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 312Example 9-9. Verilog Mealy State Machine . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 313Example 10-1. Verilog DSP MULT-ADD . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 321Example 10-2. VHDL DSP MULT-ADD . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 322Example 10-3. Verilog DSP MULT-ADDSUB . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 323Example 10-4. VHDL DSP MULT-ADDSUB . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 324Example 10-5. Verilog DSP MULT-ACC. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 325Example 10-6. VHDL DSP MULT-ACC . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 326Example 10-7. Verilog DSP MULT-ACC-ADDSUB. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 327Example 10-8. VHDL DSP MULT-ACC-ADDSUB . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 328Example 10-9. Verilog Fully Pipelined 35x18 Multiplier . . . . . . . . . . . . . . . . . . . . . . . . . . . 330Example 10-10. VHDL Fully Pipelined 35x18 Multiplier . . . . . . . . . . . . . . . . . . . . . . . . . . 331Example 10-11. Verilog DSP48 Instantiation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 332Example 10-12. VHDL DSP48 Instantiation. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 333

Page 12: PrecisionRTL Style

Precision Synthesis Style Guide, 2011a Update2 12November 2011

List of Figures

Figure 4-1. SystemVerilog File Settings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 122Figure 8-1. Asynchronous ROM Mapped into Block RAM . . . . . . . . . . . . . . . . . . . . . . . . . 249Figure 8-2. How to Set rom_block Attribute in VHDL. . . . . . . . . . . . . . . . . . . . . . . . . . . . . 249Figure 8-3. How to Set rom_block Attribute in Verilog . . . . . . . . . . . . . . . . . . . . . . . . . . . . 250Figure 8-4. VHDL ROM Implemented Using CASE Statement. . . . . . . . . . . . . . . . . . . . . . 250Figure 8-5. VHDL ROM Implement Using Array of Constants . . . . . . . . . . . . . . . . . . . . . . 251Figure 8-6. VHDL Memory Initialization Example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 252Figure 8-7. Verilog ROM Using CASE Statement . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 253Figure 8-8. Verilog ROM Using Array of Constants . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 254Figure 8-9. Verilog ROM Initialization Using $readmemh Function . . . . . . . . . . . . . . . . . . 255Figure 8-10. Verilog ROM Initialization Using $readmemb Function . . . . . . . . . . . . . . . . . 255Figure 9-1. Setting FSM encoding Style . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 295Figure 10-1. Adding dedicated_mult via the GUI . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 316Figure 10-2. DSP MULT-ADD . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 321Figure 10-3. DSP MULT-ADDSUB . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 323Figure 10-4. DSP MULT-ACC . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 325Figure 10-5. DSP MULT-ACC-ADDSUB . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 327Figure 10-6. 35x18 Multiplier Implemented in 18-bit Blocks. . . . . . . . . . . . . . . . . . . . . . . . 329Figure 10-7. Partial Products used to Build 35x18 Mult . . . . . . . . . . . . . . . . . . . . . . . . . . . . 329

Page 13: PrecisionRTL Style

13November 2011

Precision Synthesis Style Guide, 2011a Update2

List of Tables

Table 3-1. Operators Supported by Precision RTL Synthesis . . . . . . . . . . . . . . . . . . . . . . . 91Table 4-1. Supported SystemVerilog Constructs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 119Table 4-2. SystemVerilog Examples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 152Table 5-1. VHDL and Verilog Operator Differences . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 169Table 5-2. Arithmetic Examples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 172Table 6-1. VHDL and Verilog Boolean Operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 189Table 6-2. Boolean Logic Examples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 193Table 7-1. Register Examples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 209Table 8-1. Supported Byte-Enable Device Families . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 256Table 8-2. Memory Examples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 265Table 9-1. FSM Examples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 303Table 10-1. DSP Code Examples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 320Table 11-1. Exemplar Package Attributes Recognized by the VHDL Parser . . . . . . . . . . . 338

Page 14: PrecisionRTL Style

List of Tables

14November 2011

Precision Synthesis Style Guide, 2011a Update2

Page 15: PrecisionRTL Style

Precision Synthesis Style Guide, 2011a Update2 15November 2011

Chapter 1VHDL Language Features

VHDL is a high level description language for system and circuit design. The language supportsvarious levels of abstraction. In contrast to regular netlist formats that supports only structuraldescription and a boolean entry system that supports only dataflow behavior, VHDL supports awide range of description styles. These include structural descriptions, dataflow descriptionsand behavioral descriptions.

The structural and dataflow descriptions show a concurrent behavior. That is, all statements areexecuted concurrently, and the order of the statements is not relevant. On the other hand,behavioral descriptions are executed sequentially in processes, procedures and functions inVHDL. The behavioral descriptions resemble high-level programming languages.

VHDL allows a mixture of various levels of design entry abstraction. Precision RTL SynthesisSynthesizes will accept all levels of abstraction, and minimize the amount of logic needed,resulting in a final netlist description in the technology of your choice.

VHDL is fully simulatable, but not fully synthesizable. There are several VHDL constructs thatdo not have valid representation in a digital circuit. Other constructs do, in theory, have arepresentation in a digital circuit, but cannot be reproduced with guaranteed accuracy. Delaytime modeling in VHDL is an example.

State-of-the-art synthesis algorithms can optimize Register Transfer Level (RTL) circuitdescriptions and target a specific technology. Scheduling and allocation algorithms, whichperform circuit optimization at a very high and abstract level, are not yet robust enough forgeneral circuit applications. Therefore, the result of synthesizing a VHDL description dependson the style of VHDL that is used.

This manual is intended to give you guidelines to achieve a circuit implementation that satisfiesthe timing and area constraints set for a given target circuit, while still using a high level ofabstraction in the VHDL source code.

This chapter provides an introduction to the basic language constructs in VHDL: defining logicblocks, structural, dataflow and behavioral descriptions, concurrent and sequentialfunctionality, design partitioning and more. Precision RTL Synthesis synthesizes all levels ofabstraction, and minimizes the amount of logic needed, resulting in a final netlist description inyour technology.

Page 16: PrecisionRTL Style

Precision Synthesis Style Guide, 2011a Update216

VHDL Language FeaturesEntities and Architectures

November 2011

Entities and ArchitecturesThe basic building blocks in VHDL are Entities and Architectures. An entity describes theboundaries of the logic block. Its ports and its generics are declared here. An architecturedescribes the contents of the block in structural, dataflow and behavioral constructs.

This VHDL description shows the implementation of small_block, a block that describessome simple logic functions.

The entity describes the boundary. The port list is given with a direction (in this case in or out),and a type (bit) for each port. The name of the entity is small_block. The name of thearchitecture is rtl which is linked to the entity with the name small_block. While multiplearchitectures may exist for each entity, only one architecture may be executed. By default, thelast defined architecture is linked to the entity.

The architecture describes the contents of the small_block. The architecture starts with adeclarative region; for example, the internal signal s is declared. The architecture also has a type(bit); this is similar to the ports in the entity.

A signal is another form of an object in VHDL. All objects and expressions in VHDL arestrongly typed. This means that all objects are of a defined type and issues an error message ifthere is a type mismatch. For example, you cannot assign an integer of type signal to a bit.

The architecture contents starts after the begin statement. This is called the dataflowenvironment. All statements in the dataflow environment are executed concurrently; the orderof the statements is irrelevant. This is why it is valid to use s before s is assigned anything.Assignment of a value to a signal is done with the <= sign. In the first statement, o1 is assignedthe result value of s or c. The operator or is a predefined operator.

Additional details about the various dataflow statements and operators are given in the sections:

• Configuration

• Processes

entity small_block isport (a, b, c : in bit ;

o1 : out bit ;o2 : out bit

) ;end small_block ;

architecture rtl of small_block issignal s : bit ;

begino1 <= s or c ;s <= a and b ;o2 <= s xor c ;

end rtl ;

Page 17: PrecisionRTL Style

VHDL Language FeaturesEntities and Architectures

Precision Synthesis Style Guide, 2011a Update2 17November 2011

Entity and Package HandlingPackages and entities in VHDL are stored in libraries. You can load VHDL files (with packagesand entities) separately into a directory that is assigned as a resource library.

An example of a predefined package is the package STANDARD (which ispre-defined for VHDL), that Precision RTL Synthesis loads from file standard.vhd in<precision install directory>/pkgs/techdata/vhdl.

Precision RTL Synthesis can handle either VHDL IEEE 1076-1987 or IEEE 1076-1993 dialectsof VHDL. The default is 93. To run 87-style VHDL, select the menu Tools > Set Options... >+Input > VHDL and click VHDL_87, or use the command:

setup_design -variable vhdl_87=TRUE

NotePrecision RTL Synthesis supports all IEEE 1076-1993 synthesizable features.

Entity Compiled as the Design RootWhen the VHDL source is read, Precision RTL Synthesis starts compiling the first file listed inthe Input Files list, then compiles the second file, and so on. By default, the last entity compiledin the source files is used as the top-level entity.

After the root (top) entity is found, Precision RTL Synthesis tries to find a matchingarchitecture. By default, the it will choose the LAST architecture described in the source VHDLfile that matches the top-level entity.

ConfigurationIn summary, a configuration declaration provides the mechanism for delayed componentbinding specification. The entity name identifies the root entity to be elaborated. The optionalarchitecture name provides the name of the architecture to be elaborated.

A configuration declaration can configure each component instantiation individually with adifferent entity or architecture. The configuration declaration can also configure some lowerlevel component instantiation of the current component being configured.

With the help of the configuration declaration, you can try out different possible bindings of thecomponent instantiations by keeping the basic hierarchical structure of the top level designintact.

Page 18: PrecisionRTL Style

Precision Synthesis Style Guide, 2011a Update218

VHDL Language FeaturesEntities and Architectures

November 2011

NoteIf you use “con” for configuration and “ent” for entity then the name of the hierarchy cellcreated is “con_ent”.

library ieee;use ieee.std_logic_1164.all;package global_decl istype log_arr is array(std_logic) of std_logic;constant std_to_bin : log_arr:=('X','X','0','1','X','X','0',

'1','X');function to_bin (from : std_logic) return std_logic;

end;

library ieee;use ieee.std_logic_1164.all;use work.global_decl.all;package body global_decl isfunction to_bin (from : std_logic) return std_logic isbeginreturn std_to_bin(from);end ;

end package body;

library ieee;library work;use ieee.std_logic_1164.all;use work.global_decl.all;

entity en1 is port(a: in std_logic;b: out std_logic);end;

architecture ar1 of en1 isbeginb <= to_bin (a);end;

architecture ar2 of en1 isbeginb <= not (to_bin (a));end;

Page 19: PrecisionRTL Style

VHDL Language FeaturesEntities and Architectures

Precision Synthesis Style Guide, 2011a Update2 19November 2011

ProcessesProcesses are sections of sequentially executed statements, as opposed to the dataflowenvironment, where all statements are executed concurrently. In a process, the statementordering does matter. In fact, processes resemble the sequential coding style of high levelprogramming languages. Also, processes offer a variety of powerful statements and constructsthat make them very suitable for high-level behavioral descriptions.

A process can be called from the dataflow area. Each process is a sequentially executedprogram, but all processes run concurrently. In a sense, multiple processes resemble multipleprograms that can run simultaneously. Processes communicate with each other via signals thatare declared in the architecture. Also, the ports defined in the entity can be used in theprocesses.

library ieee;library work;use ieee.std_logic_1164.all;use work.global_decl.all;entity en2 is port(a: in std_logic;b, c: out std_logic);end;

architecture arc of en2 iscomponent en1 port(a: in std_logic;b: out std_logic);end component;beginc1: en1 port map (a => a, b => b);c2: en1 port map (a => a, b => c);

end;

library work;configuration binding of en2 isfor arc

for c1: en1 use entity work.en1 (ar1);end for;for c2: en1 use entity work.en1 (ar2);end for;end for;end binding ;

Page 20: PrecisionRTL Style

Precision Synthesis Style Guide, 2011a Update220

VHDL Language FeaturesEntities and Architectures

November 2011

This example describes a circuit that can load a source vector of 4 bits, on the edge of a writeclock (wrclk), store the value internally in a register (intreg) if a chip enable (ce) is active,while it produces one bit of the register constantly (not synchronized). The bit is selected by aselector signals of two bits.

The description consists of two processes, one to write the value into the internal register, andone to read from it. The two processes communicate via the register value intreg.

The first process (writer) includes a wait statement. The wait statement causes the process toexecute only if its condition is TRUE. In this case, the wait statement waits until a positive edgeoccurs on the signal wrclk (expression wrclk’event and wrclk=’1’). Each time the edgeoccurs, the statements following the wait statements are executed. In this case, the value of theinput signal source is loaded into the internal signal intreg only if ce is ’1’. If ce is ’0’,

entity experiment isport ( source : in bit_vector(3 downto 0) ;

ce : in bit ;wrclk : in bit ;selector : in bit_vector(1 downto 0) ;result : out bit

);end experiment;

architecture rtl of experiment issignal intreg : bit_vector(3 downto 0) ;

begin -- dataflow environmentwriter : process -- process statement

-- declarative region (empty here)begin -- sequential environment

-- sequential (clocked) statementswait until wrclk’event and wrclk = ’1’ ;if (ce=’1’) then

intreg <= source ;end if ;

end process writer;

reader : process (intreg, selector) -- process statement-- with sensitivity list-- declarative region (empty here)

begin-- sequential (not-clocked) statements

case selector iswhen "00" => result <= intreg(0) ;when "01" => result <= intreg(1) ;when "10" => result <= intreg(2) ;when "11" => result <= intreg(3) ;

end case ;end process reader;

end rtl ;

Page 21: PrecisionRTL Style

VHDL Language FeaturesLiterals

Precision Synthesis Style Guide, 2011a Update2 21November 2011

intreg retains its value. In synthesis terms, this translates into a D-flipflop, clocked on wrclk,and enabled by ce.

The second process (reader) does not have a wait statement. Instead, it has a sensitivity list,with the signals intreg and selector there. This construct defines that the whole process isexecuted each time either intreg or selector changes. If the process is executed, the outputsignal result gets updated with depending on the values of intreg and selector. Note thatthis leads to combinational behavior, since result depends on only intreg and selector, andeach time either of these signals changes, result gets updated.

A process has an optional name (in this case writer and reader), a sensitivity list OR a waitstatement, and a declarative region where signals, variables, functions etc. can be declaredwhich are used only within the process. Each statement is executed sequentially, as in aprogramming language.

Not all constructs, or combinations of constructs, in a process lead to behavior that can beimplemented as logic.

LiteralsConstant values in VHDL are given in literals. Literals are lexical elements. The following is anoverview, with examples given for each type of literal.

Literals are used to define types and as constant values in expressions. This list provides a briefdescription of their function in VHDL which will be more clear after the descriptions of typesand expressions.

The ’_’ in bit string literals, decimal literals and based literals helps to order your literal, butdoes not represent a value.

Character literals contain only a single character, and are single quoted.

String literals contain an array of characters, and are double quoted.

Character Literals: ’0’ ’X’ ’a’ ’%’ #

String Literals: “1110100” “XXX” “try me!” “$^&@!”

Bit String Literals: B“0010_0001” X”5F’ O“63_07”

Decimal Literals: 27 -5 4E3 76_562 4.25

Based Literals: 2#1001# 8#65_07" 14#C5#E+2

Physical Literals: 2 ns 5.0 V 15 pF

Identifiers: Idle TeSTing a true_story

Page 22: PrecisionRTL Style

Precision Synthesis Style Guide, 2011a Update222

VHDL Language FeaturesLiterals

November 2011

Bit String Literals are a special form of string literals. They contain an array of the characters 0and 1, and are preceded by one of three representation forms. B is the bit representation (0 or 1allowed), X the hexadecimal representation (0 to F allowed) and O the octal representation (0 to7 allowed). X"5F" is exactly the same as B"01011111", which is again the same as the stringliteral "01011111".

Bit string literals can contain underscores, which are ignored and only inserted for readability.

Decimal literals are integer or real values.

Based literals are also integer or real values, but they are written in a based form. 8#75# isthe same as decimal 61. However it is not the same as the bit literal value O"75" since the bitliteral value is an array (of bits) and the based literal is a integer.

Physical literals are sometimes required for simulation. As they are not used in the synthesizedpart of the design, we do not go into detail about them.

Identifiers can be enumerated literals. They are case-insensitive, like all identifiers in VHDL.Their use becomes more clear with the discussion of VHDL types.

TypesA type is a set of values. VHDL supports a large set of types, but here we concentrate on typesthat are useful for synthesis.

VHDL is a strongly typed language: every object in a VHDL source needs to be declared andneeds to be of a specific type. This allows the VHDL compiler to check that each object stores avalue that is in its type. This avoids confusion about the intended behavior of the object, and ingeneral allows the user to catch errors early in the design process. It also allows overloading ofoperators and subprograms. It also make coding in VHDL a little more difficult, but tends toproduce cleaner, better maintainable code.

VHDL defines four classes of types:

• Scalar types

• Composite types

• Access types

• File types

Access types and File type cannot be applied for logic synthesis, since they require dynamicresource allocation, which is not possible in a synthesized hardware. Therefore, we will notdiscuss these.

Instead, only scalar types and composite types will be discussed. These are all scalar types inVHDL:

Page 23: PrecisionRTL Style

VHDL Language FeaturesLiterals

Precision Synthesis Style Guide, 2011a Update2 23November 2011

• Enumerated types.

• Integer types

• Floating-point types

• Physical types

• VHDL has two forms of composite types:

o Array types

o Record types.

Enumerated Types

Syntax and SemanticsAn enumerated type consists of a set of literals (values). It indicates that objects of that typecannot contain any other values than the ones specified in the enumerated type.

An example of an enumerated type is the pre-defined type bit. This is how the type bit isdeclared:

Any object of type bit can only contain the (literal) values ’0’ and ’1’. The VHDL compilerwill error out (type error) if a different value could be assigned to the object.

Enumerated types are also often used to declare the (possible) states of a state machine. Here isan example of the declaration of the states of an imaginary state machine are declared:

Once an object of this type is declared, the object can contain only one of these three ‘state’values.

Integer Types

Syntax and SemanticsWhen designing arithmetic behavior, it is very helpful to work with integer types. An integertype defines the set of integer values in its range. This is how an integer type is defined:

type bit is (’0’,’1’) ;

type states is (IDLE, RECEIVE, SEND) ;

type my_integer is range 0 to 15 ;

Page 24: PrecisionRTL Style

Precision Synthesis Style Guide, 2011a Update224

VHDL Language FeaturesLiterals

November 2011

Any object of type my_integer can only contain integer values in the range specified. VHDLpre-defines an integer type called integer, that at least covers a range of integer values that canbe represented in two’s complement with 32 bits:

Actually, VHDL 1076 does not define the maximum bounds of the predefined type integer

nor of any other integer type, it just states that it should at least include this range.

Integer Synthesis issuesPrecision RTL Synthesis can synthesize with any integer type that contains no values outsidethe range -2147483648 to 2147483647. Precision RTL Synthesis stores integer values (constantones) using (32 bit) integers internally. If more than 32 bits are needed for a particular circuitdesign, you should use arrays to represent them. Do not use integer types that exceed the range,since many other VHDL tools have the same restrictions as Precision RTL Synthesis.

Precision RTL Synthesis needs to do encoding for integer types, since an integer range requiresmultiple bits to represent. The synthesis tools will analyze the range of an integer type andcalculate the number of bits needed to represent it.

If there are no negative values in the integer range, Precision RTL Synthesis will create anunsigned representation. For example, consider the following object of the type my_integer

from the previous section:

The signal count will be represented as unsigned, consisting of four bits. When synthesized, thefour bits will be named as elements of a bus in the resulting netlist:

If the range includes negative numbers, Precision RTL Synthesis will use two’s-complementrepresentation of the integer values. For example, any object of the predefined type integer

will be represented with 32 bits where the MSB bit represents the sign bit.

Example:

type integer is range -2147483647 to 2147483647;

signal count : my_integer ;

count(3) the MSB bitcount(2)count(1)count(0) the LSB bit

signal big_value : integer ;

Page 25: PrecisionRTL Style

VHDL Language FeaturesLiterals

Precision Synthesis Style Guide, 2011a Update2 25November 2011

Now, Precision RTL Synthesis will represent the signal big_value as 32 bits:

Floating-point Types

Syntax and SemanticsAs any high-level programming language, VHDL defines floating-point types. Floating-pointtypes approximate the real numbers.

Here is an example of the declaration of a floating-point type:

VHDL pre-defines a very general floating-point type called real.

Like the integer types, maximum bounds of any floating-point type are not defined by thelanguage. However, the floating-point type should but should at least include -1.0E38 to1.0E38.

Nothing in the language defines anything about the accuracy of the resolution of the floating-point type values.

Synthesis Issues for Floating-point TypesIn general, since the resolution of floating-point types is not defined by the language, it isdifficult to come up with a good rule for encoding floating-point types. While in a regular(software) compilers floating-point types are represented in 32, 64 or 128 bits, the floating-pointoperations just require time. In hardware compilers like a logic synthesis tool, floating-pointoperations would require massive amounts of actual synthesized hardware, unless the resolutionand bounds of the floating-point type are kept under very close control.

In summary, Precision RTL Synthesis does not currently support synthesis of floating pointobjects. Floating-point types and objects can however be used in constant expression.

big_value(31) the sign bitbig_value(30) the MSB bit::big_value(1)big_value(0) the LSB bit

type my_real is range 0.0 to 1.0 ;

type real is range -1.0E38 to 1.0E38 ;

Page 26: PrecisionRTL Style

Precision Synthesis Style Guide, 2011a Update226

VHDL Language FeaturesLiterals

November 2011

For example, an attribute could get a (compile time constant) floating-point expression, and thesynthesis tools will calculate the expression and set the floating-point value on the attribute.

Physical Types

Syntax and SemanticsVHDL allows the definition of physical types. Physical types represent relations betweenquantities. A good example of a physical type is the predefined type time:

Objects of physical types can contain physical values of the quantities specified in the type, aslong as the values do not exceed the range of the type. Type time is often used in VHDLdesigns to model delay.

Synthesis Issues for Physical TypesPhysical types, objects and values are normally only used for simulation purposes. Objects andvalues of type time are used in after clauses to model delay.

Precision RTL Synthesis attempts to synthesize any physical value that is within the range ofthe type. The encoding follows the encoding for integer types, and expresses the value withrespect to the base quantity (fs in the type time). It is not common practice however tosynthesize logic circuitry to model physical values.

Precision RTL Synthesis handles constant expressions of physical values without any problems.For example, attributes of type time can receive constant values of type v. This is often used tomodel arrival time and required time properties in the design.

Array Types

Syntax and SemanticsAn array type in VHDL specifies a collection of values of the same type. There are constrainedand unconstrained array types.

type time is range -2147483647 to 2147483647units

fs;ps = 1000 fs;ns = 1000 ps;us = 1000 ns;ms = 1000 us;sec = 1000 ms;min = 60 sec;hr = 60 min;

end units;

Page 27: PrecisionRTL Style

VHDL Language FeaturesLiterals

Precision Synthesis Style Guide, 2011a Update2 27November 2011

For an constrained array type, the number of elements and the name of the elements (the index)is defined and fixed.

Example:

In this example, type byte defines an array of 8 element, each of type bit. The elements arenamed with indexes ranging from 7 (for the left most element in the array) downto 0 (for theright most element in the array). Example of an array object:

Individual elements of the array object can now be referred to using indexing:

seven(0) is the name of the right most element in array v. Its value is the bit literal ’1’.

seven(7) is the name of the left most element in array v. Its value is the bit literal ’0’.

Parts of the array can be retrieved using slicing:

seven(3 downto 0) is the name of the right most four elements in array seven. The value is anarray of four bits: "0111". The indexes of this array range from 3 down to 0.

For an unconstrained array type, the number of elements and the name of the elements in not yetdefined. An example is the pre-defined type bit_vector:

Here, the array type defines that the element type is bit, and that the index type is typenatural. Type natural is an integer subtype that includes all non-negative integers. Themeaning of this is that the index value for any object of type bit_vector can never be negative.

By defining an unconstrained array type, you defer specifying a size for the array. Still, in orderto define a valid object of an unconstrained array type, we need to constrain the index range.This is normally done on the object declaration:

Unconstrained array types are very important, since they allow you to declare many different-size objects and to use these objects through each other, without introducing type conflicts.

type byte is array (7 downto 0) of bit ;

constant seven : byte := "00000111" ;

type bit_vector is array (natural range <>) of bit ;

constant eight : bit_vector (7 downto 0) := "00001000" ;

Page 28: PrecisionRTL Style

Precision Synthesis Style Guide, 2011a Update228

VHDL Language FeaturesLiterals

November 2011

The type of the element of an (constrained or unconstrained) array type is not restricted toenumerated type bit as in the examples. Actually, an array element type can be any type exceptfor an unconstrained array type.

You can define an array of integers, an array of 6-bit arrays, an array of records etc. However,you cannot declare an array of (the unconstrained array type) bit_vector.

If you want an unconstrained array type where you need more indexes to remain unconstrained,you need a multi-dimensional array type:

Multi-dimensional (constrained and unconstrained) array type are useful when modelingRAMs, ROMs and PLAs in VHDL. Indexes and slices of multi-dimensional arrays need tospecify all index dimensions, separated by a comma.

Finally, the index type of an array type does not have to be an integer (sub)type. It can also be anenumerated type.

Synthesis Issues for Array TypesThere are no synthesis restrictions in Precision RTL Synthesis on using arrays. Precision RTLSynthesis supports arrays of anything (within the language rules), multi-dimensional arrays,array types with enumerated index type. Negative indexes are also allowed.

Naming of array objects is straightforward. Precision RTL Synthesis appends the index for eachelement after the array name. If the element type consists of multiple bits, the synthesis toolsappend the element indexes to the array name with its index.

It is important to understand that there is no Most Significant Bit (MSB) or Least Significant Bit(LSB) defined in an array type or array object. The semantics of what is interpreted as MSB orLSB is defined by the operations on the array. In the example of object seven the user probablymeant the left most bit to be the MSB, and the right most bit the LSB. However, this is notdefined by the language, just by the user.

Additions, subtractions, and multiplications have to be defined by the user. Most synthesis toolvendors define (arithmetic) operations on arrays in packages that are shipped with the product.Most of these packages assume that leftmost bit is the MSB and the rightmost bit is the LSB. Asan example of this, the packages exemplar and exemplar_1164 define arithmetic operators thebit_vector and the IEEE 1164 array equivalent std_logic_vector type. In these packages,the leftmost bit is assumed to be the MSB.

type matrix is array (natural range <>, natural range <>) of bit ;

Page 29: PrecisionRTL Style

VHDL Language FeaturesLiterals

Precision Synthesis Style Guide, 2011a Update2 29November 2011

Record Types

Syntax and SemanticsA record type defines a collection of values, just like the array type.

All elements of an array must be of the same type. Elements of a record can be of differenttypes:

The element type month_name in this example could be an enumerated type with all names ofthe months as literals.

The elements of a record type can again be of any type, but cannot be an unconstrained array.

Consider the following object of type date:

Individual elements of a record object can be accessed with a selected name. A selected nameconsists of the object name, followed by an underscore(_) and the element name:

my_birthday_year selects the year field out of my_birthday and returns the integer value 1963.

Synthesis Issues for Record TypesPrecision RTL Synthesis does not impose any restrictions (except for language rules) on recordtypes and record objects.

Naming of the individual bits that result after synthesizing a record object follow the selectednaming rule of the language: Each bit in a record object get the record name followed by anunderscore, followed by the element name. If the element synthesizes into multiple bits, theindex of the bits in each element are appended to that. As an example, the five bits that representthe day field in my_birthday will be named as follows:

type date isrecord

day : integer range 1 to 31 ;month : month_name ;year : integer range 0 to 4000 ;

end record ;

constant my_birthday : date := (29, june, 1963) ;

my_birthday_day(0) LSB in my_birthday.daymy_birthday_day(1)my_birthday_day(2)my_birthday_day(3)my_birthday_day(4) MSB in my_birthday.day

Page 30: PrecisionRTL Style

Precision Synthesis Style Guide, 2011a Update230

VHDL Language FeaturesLiterals

November 2011

SubtypesA subtype is a type with a constraint.

A subtype allows you to restrict the values that can be used for an object without actuallydeclaring a new type. This speeds up the debugging cycle, since the simulator will do a run-timecheck on values being out of the declared range. Declaring a new type would cause typeconflicts. Here is an example:

With a type-conversion (see next section), you can ’cast’ one integer into another one to avoidthe error. Still, it is cleaner to use a subtype declaration for the (more constrained)small_integer type:

Subtypes can be used to constraint integer types (as in the example), floating-point type, andunconstrained arrays.

Declaring a subtype that constraints an unconstrained array type is exactly the same as declaringa constrained array type:

subtype <subtype_name> is <base_type> [<constraint>] ;

type big_integer is range 0 to 1000 ;type small_integer is range 0 to 7;

signal intermediate : small_integer ;signal final : big_integer ;

final <= intermediate * 5 ; <- type error occurs because big_integer and small_integer are NOT the same type

type big_integer is range 0 to 1000 ;subtype small_integer is big_integer range 0 to 7;

signal intermediate : small_integer ;signal final : big_integer ;

final <= intermediate * 5 ;<- NO type error occurs ! becausebig_integer and small_integerhave the same base-type(big_integer).

type bit_vector is array (natural range <>) of bit ;subtype eight_bit_vector is bit_vector (7 downto 0) ;

Page 31: PrecisionRTL Style

VHDL Language FeaturesLiterals

Precision Synthesis Style Guide, 2011a Update2 31November 2011

has the same effect as:

Just as in the integer type example, subtypes of one and the same unconstrained base-type arecompatible (will not cause type errors), but when two constrained array types are used, they willcause type errors if objects of both types are intermixed in expressions. Type conversion is thenthe only possibility to let objects of the two types be used together in expressions without typeerrors. There are no synthesis restrictions on the use of subtypes.

Type ConversionsIn cases where it is not possible to declare one type and one subtype instead of two separatetypes, VHDL has the concept of type conversion. Type conversion is similar to type ’casting’in high level programming languages. To cast an expression into a type, use the followingsyntax:

Type conversion is allowed between ’related’ types. There is a long and detailed discussion inthe VHDL LRM about what related types are, but in general, if it is obvious to you that thecompiler should be able to figure out how to translate values of one type to values of anothertype, the types are probably related. For example, all integer types are related, all floating-pointtypes are related and all array types of the same element type are related.

So, the problem of type error between two different types in example of the previous sectioncould be solved with a type conversion:

type eight_bit_vector is array (7 downto 0) of bit ;

<type>(<expression>)

type big_integer is range 0 to 1000 ;type small_integer is range 0 to 7;

signal intermediate : small_integer ;signal final : big_integer ;

final <= big_integer(intermediate * 5) ;<- NO type error occurs now,since the compiler knows how totranslate ’small_integer’ intobig_integer with the typeconversion.

Page 32: PrecisionRTL Style

Precision Synthesis Style Guide, 2011a Update232

VHDL Language FeaturesLiterals

November 2011

IEEE 1076 Predefined TypesThe VHDL IEEE 1076 standard predefines a number of types. The following lists the oneswhich are most important for synthesis:

Precision RTL Synthesis also understands the predefined types CHARACTER, STRING,SEVERITY_LEVEL, TIME, REAL and FILE.

IEEE 1164 Predefined TypesA problem with the 1076 standard is that it does not specify any multi-valued logic types forsimulation purposes, but rather left this to the user and/or tool vendor. The IEEE 1164 Standardspecifies a 9-valued logic. Precision RTL Synthesis supports these types, although somerestrictions apply to the values you can use for synthesis.

The meaning of the different type values of the IEEE 1164 standard are as follows:

’U’ Uninitialized

’X’ Forcing Unknown

’0’ Forcing Low

’1’ Forcing High

’Z’ High Impedance

’W’ Weak Unknown

’L’ Weak Low

’H’ Weak High

’-’ Dont Care

The weak values on a node can always be overwritten by a forcing value. The high impedancestate can be overwritten by all other values.

Most of these values are meaningful for simulation purposes only. Some restrictions apply ifyou want to use these values for synthesis. Only the values ’0’,’1’,’X’,’-’ and ’Z’ have awell-described meaning for synthesis.

type bit is (’0’,’1’) ;type bit_vector is array (integer range <>) of bit ;type integer is range MININT to MAXINT ;subtype positive is integer range 0 to MAXINT ;subtype natural is integer range 0 to MAXINT ;type boolean is (TRUE,FALSE) ;

Page 33: PrecisionRTL Style

VHDL Language FeaturesObjects

Precision Synthesis Style Guide, 2011a Update2 33November 2011

Some examples of IEEE 1164 type statements are:

The identifier resolution_func is a function that defines which value should be generated incase multiple values are assigned to an object of the same type. This is called the resolutionfunction of the type. Resolution functions are supported as long as they do not return anymetalogical values.

To use the IEEE 1164 types you must load the IEEE package into your VHDL description. Thisis done with the following statements:

ObjectsObjects in VHDL (signals, variables, constants, ports, loop variables, generics) can containvalues. Values can be assigned to objects, and these values can be used elsewhere in thedescription by using the object in an expression. All objects except loop variables have to bedeclared before they are used. This section describes the various objects in VHDL and theirsemantics.

SignalsSignals represent wires in a logic circuit. Here are a few examples of signal declarations:

Signals can be declared in all declarative regions in VHDL except for functions and procedures.The declaration assigns a name to the signal (foo); a type, with or without a range restriction(bit_vector(5 downto 0)); and optionally an initial (constant) value. Initial values onsignals are usually ignored by synthesis.

Signals can be assigned values using an assignment statement(e.g., aux <= ’0’ ;). If the signal is of an array type, elements of the signal’s array can beaccessed and assigned using indexing or slicing.

type std_ulogic is (’U’,’X’,’0’,’1’,’Z’,’W’,’L’,’H’,’-’) ;type std_ulogic_vector is array (natural range <>) of std_ulogic ;subtype std_logic is resolution_func std_ulogic ;type std_logic_vector is (natural range <>) of std_logic ;subtype X01Z is resolution_func std_ulogic range ’X’ to ’Z’ ;

-- includes X,0,1,Z

library ieee ;use ieee.std_logic_1164.all ;

signal foo : bit_vector (5 downto 0) := B"000000" ;signal aux : bit ;signal max_value : integer ;

Page 34: PrecisionRTL Style

Precision Synthesis Style Guide, 2011a Update234

VHDL Language FeaturesObjects

November 2011

Assignments to signals are not immediate, but scheduled to be executed after a delta delay. Thiseffect is an essential difference between variables and signals.

ConstantsConstants can not be assigned a value after their declaration. Their only value is the initialconstant value. Initialization of a constant is required. An example of declaring a constant is:

VariablesVariables can not be declared or used in the dataflow areas or in packages, only in processes,functions and procedures. An example of declaring a variable is:

Assignments to a variable are immediate. This effect is an essential difference betweenvariables and signals. The initial assignment to a variable is optional. The initial assignment to avariable in a process is usually ignored by synthesis.

PortsA port is an interface terminal of an entity. A port represents an ordinary port in a netlistdescription. Ports in VHDL are, just like other objects, typed and can have an initial value. Inaddition, a port has a “direction.” This is a property that indicates the possible information flowthrough the port. Possible directions are in, out, inout and buffer, where inout and buffer

indicate bidirectional functionality.

After declaration, a port can be used in the architecture of the entity as if it were a normal signal,with the following restrictions: first, you cannot assign to a port with direction in, and second,you cannot use a port of direction out in an expression.

constant ZEE_8 : std_logic_vector (7 downto 0) := "ZZZZZZZZ" ;

variable temp : integer range 0 to 10 := 5 ;

entity adder isport (

input_vector : in bit_vector (7 downto 0) ;output_vector : out bit_vector (7 downto 0)

) ;end adder ;

Page 35: PrecisionRTL Style

VHDL Language FeaturesStatements

Precision Synthesis Style Guide, 2011a Update2 35November 2011

GenericsA generic is a property of an entity. A good example of a generic is the definition of the size ofthe interface of the entity. Generics are declared in a generic list.

The generic size can be used inside the entity (e.g., to define the size of ports) and in thearchitecture that matches the entity. In this example, the generic size is defined as an integerwith an initial value 8. The sizes of the input and output ports of the entity increment are set tobe 8 bits unless the value of the generic is overwritten by a generic map statement in thecomponent instantiation of the entity.

Here, a 16-bit incrementer is instantiated, and connected to the signals invec and outvec.

Precision RTL Synthesis fully supports generics and generic map constructs and imposes norestriction on the type of the generic (such as integer, positive, natural, real, string,std_logic,std_logic_vector, boolean, or time). Generics are very useful in generalizing your VHDLdescription for essential properties like sizes of interfaces or for passing timing information forsimulation to instantiated components.

Loop VariablesA loop variable is a special object in the sense that it does not have to be declared. The loopvariable gets its type and value from the specified range in the iteration scheme.

In this code fragment, i becomes an integer with values 0,1,2...5 respectively, when the loopstatements are executed 6 times. A loop variable can only be used inside the loop, and there canbe no assignments to the loop variable. For synthesis, the range specified for the loop variablemust be a compile-time constant, otherwise the construct is not synthesizable.

StatementsThis section briefly discusses the basic statements that can be used in VHDL descriptions.

entity increment isgeneric ( size : integer := 8 ) ;port ( ivec : in bit_vector (size-1 downto 0) ;

ovec : out bit_vector (size-1 downto 0)) ;end increment ;

inst_1 : increment generic map (size=>16)port map (ivec=>invec, ovec=>outvec) ;

for i in 5 downto 0 loopa(i) <= b(i) and ena ;

end loop ;

Page 36: PrecisionRTL Style

Precision Synthesis Style Guide, 2011a Update236

VHDL Language FeaturesStatements

November 2011

Conditional Statements

This code fragment describes a multiplexer function, implemented with an if-then-elsestatement. This statement can only be used in a sequential environment, such as a process,procedure or a function.

The same functionality in the dataflow environment is accomplished with the use of theconditional signal assignment statement:

Selection StatementsIf many conditional clauses have to be performed on the same selection signal, a case statementis a better solution than the if-then-else construct:

The “|” sign indicates that particular case has to be entered if any of the given choices is true(or functionality). Each case can contain a sequence of statements.

signal a : integer ;signal output_signal, x, y, z : bit_vector (3 downto 0) ;....if a = 1 then

output_signal <= x ;elsif a = 2 then

output_signal <= y ;elsif a = 3 then

output_signal <= z ;else

output_signal <= "0000" ;end if ;

signal a : integer ;signal output_signal, x, y, z : bit_vector (3 downto 0) ;....output_signal <= x when a=1 elsey when a=2 elsez when a=3 else"0000" ;

signal output_signal, sel, x, y, z : bit_vector (3 downto 0) ;....case sel is

when "0010" => output_signal <= x ;when "0100" => output_signal <= y ;when "1000" => output_signal <= z ;when "1010" | ”1100" | "0110" => output_signal <= x and y and z ;when others => output_signal <= "0000" ;

end case ;

Page 37: PrecisionRTL Style

VHDL Language FeaturesStatements

Precision Synthesis Style Guide, 2011a Update2 37November 2011

The case statement can only be used in a sequential environment. In the dataflow environment,the selected signal assignment statement has the equivalent behavior:

NoteFor additional information on the handling of others during optimization, see“Advanced FSM Optimization” on page 296 and “How Precision Implements a SafeFSM” on page 297.

Loop Statements and Generate StatementsIn many cases, especially with operations on arrays, many statements look alike, but differ onlyon minor points. In that case, you might consider using a loop statement.

In this code fragment, each bit of a input signal is “anded” with a single bit enable signal, toproduce an output array signal. The loop variable i does not have to be declared. It holds aninteger value since the loop range is an integer range.

The previous example showed a for loop. VHDL also has a while loop. Here is an example:

Precision RTL Synthesis supports almost every type of loop. The tool supports any for loopwith the exception of for loops that contain wait until statements. The tool also supports any

signal output_signal, sel, x, y, z : bit_vector (3 downto 0) ;....with sel select

output_signal <= x when "0010",y when "0100",z when "1000",x and y and z when "1010" | "1100"|"0110", "0000" when others ;

signal result, input_signal : bit_vector (5 downto 0) ;signal ena : bit ;....for i in 0 to 5 loop

result(i) <= ena and input_signal(i) ;end loop ;

process -- no sensitivity listbegin

wait until clk’ event AND clk=’1’;output_signal <= 0;

while (input_signal < 6) loopwait until clk’ event AND clk=’1’;output_signal <= output_signal +1;end loop;end process;

Page 38: PrecisionRTL Style

Precision Synthesis Style Guide, 2011a Update238

VHDL Language FeaturesStatements

November 2011

kind of NEXT and EXIT statements applicable on an outer while loop with multiple wait

statements.

While loops are supported as long as they have a valid wait statement in every possible pathwithin the loop. If a while loop does not have a single wait statement, and it is bound byconstants, then the tool synthesized the design correctly. This is shown in the followingexample:

The tool supports EXIT and NEXT statements within while loops.

For example, we could write the while loop as follows:

The loop statement can only be used inside sequential environments. Its equivalent statement inthe dataflow environment is the generate statement:

The generate statement is preceded by a label (G1). A label is required in the generatestatement but is optional in the loop statement.

The generate statement does not allow EXIT and NEXT statements. The reason is that thestatements inside the generate statement are executed concurrently. So there is no way to

variable i : integer ; ......i := 0 ;while (i < 6) loop

result(i) <= ena AND input_signal(i) ;i := i + 1 ;

end loop ;

process -- no sensitivity listbegin

wait until clk’ event AND clk=’1’;output_signal <= 0;

while (TRUE) loopexit if (input_signal < 6);wait until clk’ event AND clk=’1’;output_signal <= output_signal +1;end loop;end process;

signal result, input_signal : bit_vector (5 downto 0) ;signal ena : bit ;....G1 : for i in 0 to 5 generate

result(i) <= ena and input_signal(i) ;end generate ;

Page 39: PrecisionRTL Style

VHDL Language FeaturesStatements

Precision Synthesis Style Guide, 2011a Update2 39November 2011

know when to exit. The generate statement has no while equivalent, for the same reason.Instead however, there is a if equivalent in the generate statement:

The condition must evaluate to a run-time constant. That is a language requirement.

There is no else part possible in a generate statement. We consider this a flaw in the language,but Mentor Graphics synthesis tools have to comply with it.

Precision RTL Synthesis does not have any synthesis restrictions for the generate statement.

Assignment StatementsAssignments can be done to signals, ports and variables in VHDL. Assignments to signals andports are done with the <= operator.

In this code fragment o gets assigned the value of the vector-XOR (bit by bit) of vectors v and b.The type of the object on the left hand side of the assignment should always match the type ofthe value on the right hand side of the assignment. Signal assignments can be used both indataflow environment and sequential environments.

Assignments to variables are done with the “:=” sign.

Variable assignments can only be used in sequential environments. Types on left and right handside of the “:=” sign should match.

There is one important difference between assignments to signals and assignments to variables:when the values are updated. The value of a variable in a variable assignment is updated

signal result, input_signal : bit_vector (5 downto 0) ;G1 : for i in 0 to 5 generateG2 : if i < 3 generate

result(i) <= input_signal(i) ;end generate ;G3 : if (i >= 4) generate

result(i) <= NOT input_signal (i);end generate ;end generate ;

signal o, a, b : std_logic_vector (5 downto 0) ;....o <= a xor b ;

variable o : std_logic_vector (5 downto 0) ;signal a, b : std_logic_vector (5 downto 0) ;....o := a AND NOT b ;

Page 40: PrecisionRTL Style

Precision Synthesis Style Guide, 2011a Update240

VHDL Language FeaturesStatements

November 2011

immediately after the assignment. The value of a signal in a signal assignment is not updatedimmediately, but gets “scheduled” until after a delta (delay) time.

This delay time is not related to actual time, but is merely a simulation characteristic. Thisbehavior of the signal assignment does not have any effect for signal assignments in a dataflowenvironment, since assignments are done concurrently there. However, in a process, the actualvalue of the signal changes only after the complete execution of the process.

The following example illustrates this effect. It shows the description of a multiplexer that canselect one bit out of a four bit vector using two select signals.

This description does not behave as intended. The problem is because muxval is a signal; thevalue of muxval is not immediately set to the value defined by bits a and b. Instead, muxval stillhas the same value it had when the process started when the if statement is executed. Allassignments to muxval are scheduled until after the process finishes. This means that muxvalstill has the value it got from the last time the process was executed, and that value is used toselect the bit from the input vector.

entity mux isport ( s1, s2 : in bit ;

inputs : in bit_vector (3 downto 0) ;result : out bit

) ;end mux ;

architecture wrong of mux isbegin

process (s1,s2,inputs)signal muxval : integer range 0 to 3 ;begin

muxval <= 0 ;if (s1 = '1') then muxval <= muxval+1 ;end if;if (s2 = '1') then muxval <= muxval+2 ;end if;-- use muxval as index of array ’inputs’result <= inputs (muxval) ;

end process ;end wrong ;

Page 41: PrecisionRTL Style

VHDL Language FeaturesOperators

Precision Synthesis Style Guide, 2011a Update2 41November 2011

The solution to this problem is to make muxval a variable. In that case, all assignments done tomuxval are immediate, and the process works as intended.

As a general rule, if you use signal assignments in processes, do not use the value of the signalafter the assignment, unless you explicitly need the previous value of the signal. Alternatively,you can use a variable instead.

Operators

IEEE 1076 Predefined OperatorsVHDL predefines a large number of operators for operations on objects of various types. Thefollowing is an overview:

Relational operators on ALL types (predefined or not):

Logical operators on pre-defined types BIT and BOOLEAN:

entity mux isport ( s1, s2 : in bit ;

inputs : in bit_vector (3 downto 0) ;result : out bit) ;

end mux ;

architecture right of mux isbegin

process (s1,s2,inputs)variable muxval : integer range 0 to 3 ;begin

muxval := 0 ;if (s1 = ’1’) then muxval := muxval+1 ;end if;if (s2 = ’1’) then muxval := muxval+2 ;end if;-- Use muxval as index of array ’inputs’result <= inputs (muxval) ;

end process ;end right ;

= <=

/= >

< >=

AND NOR

OR XOR

NAND NOT

Page 42: PrecisionRTL Style

Precision Synthesis Style Guide, 2011a Update242

VHDL Language FeaturesOperators

November 2011

Arithmetic operators on all integer types:

Concatenation of elements into an array of elements:

Relational operators operate on any type. The basis of comparing two values is derived from theorder of definition. For example in the std_logic type the value ’U’ is smaller than the value’1’ because ’U’ is defined first in the order of values in the type. The comparison of two arraysis accomplished by comparing each element of the array. The left most element is the mostsignificant one for comparisons.

In this example, a(7) is the most significant bit for comparisons with vector a, and b(9) is themost significant bit for comparisons with vector b.

Logical operators work in a straightforward manner and do the appropriate operations on typesBIT and BOOLEAN, and also for one-dimensional arrays of BIT and BOOLEAN. In the latter case,the logical operation is executed on each element of the array. The result is an array with thesame size and type as the operands.

Arithmetic operators work on integers and on all types derived from integers. Precision RTLSynthesis supports arithmetic operators on vectors, described in the exemplar package.

+ mod

- rem

* abs

/

**

& (,,,,)

signal a : bit_vector (7 downto 0) ;signal b : bit_vector (9 downto 5) ;

Page 43: PrecisionRTL Style

VHDL Language FeaturesOperators

Precision Synthesis Style Guide, 2011a Update2 43November 2011

Concatenation operators can group elements of the same type into an array of that type.Consider the following examples:

This description is the same as the following one:

The aggregate operator in VHDL is especially useful when assigning to a vector of unknown orlarge size:

In this example, o(0) is assigned ’1’ and all other elements of o (independent of its size) getvalue ’0’.

IEEE 1164 Predefined OperatorsThe IEEE 1164 standard logic package describes a set of new types for logic values. However,the binary operators that are predefined in VHDL only operate on bit and boolean types, andarrays of bits and booleans. Therefore, the IEEE standard logic type package redefines thelogical operators (and, or, not, etc.) for the types std_logic, std_ulogic and the array typesstd_logic_vector and std_ulogic_vector.

signal a, b, c : bit ;signal x : bit_vector (5 downto 0) ;signal y : bit_vector (3 downto 0) ;....-- using concatenation operator

x <= a & b & c & B"00" & ’0’ ;-- using an aggregate

y <= (’1’, ’0’, b, c) ;

signal a, b, c : bit ;signal x : bit_vector (5 downto 0) ;signal y : bit_vector (3 downto 0) ;....

x(5) <= a ;x(4) <= b ;x(3) <= c ;x(2 downto 0) <= "000" ;y(0) <= ’1’ ;y(1) <= ’0’ ;y(2) <= b ;y(3) <= c ;

signal o : bit_vector (255 downto 0) ;....

o <= (0=>’1’,others=>’0’) ;

Page 44: PrecisionRTL Style

Precision Synthesis Style Guide, 2011a Update244

VHDL Language FeaturesAttributes

November 2011

Operator OverloadingThe operators +, -, *, mod, abs, < ,>, etc. are predefined for integer and floating-point types, andthe operators and, or, not etc. are predefined on the type bit and boolean. If you want to usean operator that is not pre-defined for the types you want to use, use operator overloading inVHDL to define what the operator should do. Suppose you want to add an integer and a bitaccording to your own semantics, and you want to use the “+” operator:

The first “+” in the assignment to t is the pre-defined “+” operator on integers. The second “+”is the user defined overloaded operator that adds a bit to an integer. The “ character around the“+” operator definition is needed to distinguish the operator definition from a regular functiondefinition.

Operator overloading is also necessary if you defined your own logic type and would like to useany operator on it.

If you want to do arithmetic operations (+, -, etc.) on the array types bit_vector orstd_logic_vector, it will be more efficient for synthesis to use the pre-defined operators fromthe exemplar and the exemplar_1164 packages.

Precision RTL Synthesis fully supports operator overloading as described by the language.

AttributesIn VHDL, attributes can be set on a variety of objects, such as signals and variables, and manyother identifiers, like types, functions, labels etc.

An attribute indicates a specific property of the signal, and is of a defined type. Using attributesat the right places creates a very flexible style of writing VHDL code. An example of this isgiven at the end of this section.

function “+” (a: integer; b: bit) return integer isbegin

if (b=’1’) thenreturn a+1 ;

elsereturn a ;

end if ;end “+” ;signal o, t: integer range 0 to 255 ;signal b : bit ;...t <= o + 5 + b ;

Page 45: PrecisionRTL Style

VHDL Language FeaturesAttributes

Precision Synthesis Style Guide, 2011a Update2 45November 2011

VHDL Predefined AttributesVHDL pre-defines a large set of attributes for signals. The following example shows thedefinition of two vectors and the values of the VHDL predefined attributes for them.

The attributes do not have to be written in capitals; VHDL is case-insensitive for identifiers.

An important VHDL predefined attribute for synthesis is the EVENT attribute. Its value revealsedges of signals.

Mentor Graphics Predefined AttributesApart from the VHDL predefined types, Mentor Graphics also supplies a set of predefinedattributes that are specifically helpful for guiding the synthesis process or controlling down-stream tools. Refer to “Predefined Attributes” on page 338.

User-Defined AttributesAttributes can also be user defined. In this case, the attribute first has to be declared, with a type,and then its value can be set on a signal or other object. This value can then be used with the“ ’ ” construct. The following is an example:

signal vector_up : bit_vector (9 downto 4) ;signal vector_dwn : bit_vector (25 downto 0) ;....vector_up’LEFT-- returns integer 9vector_dwn’LEFT-- returns integer 25vector_up’RIGHT-- returns integer 4vector_dwn’RIGHT-- returns integer 0vector_up’HIGH-- returns integer 9vector_dwn’HIGH-- returns integer 25vector_up’LOW-- returns integer 4vector_dwn’LOW-- returns integer 0vector_up’LENGTH-- returns integer 6vector_dwn’LENGTH-- returns integer 26vector_up’RANGE -- returns range 4 to 9vector_dwn’RANGE-- returns range 25 downto 0vector_up’REVERSE_RANGE-- returns range 4 to 9vector_dwn’REVERSE_RANGE-- returns range 0 to 25

signal my_vector : bit_vector (4 downto 0) ;attribute MIDDLE : integer ;attribute MIDDLE of my_vector : signal is my_vector’LENGTH/2 ;....

my_vector’MIDDLE -- returns integer 2

Page 46: PrecisionRTL Style

Precision Synthesis Style Guide, 2011a Update246

VHDL Language FeaturesAttributes

November 2011

Using Attributes in the Source CodeTo indicate where attributes in a VHDL description are useful, consider the following example.

This example calculates the parity of the bits of a source vector, where each bit can be masked.This VHDL description is correct, but is not very flexible. Suppose the application changesslightly and requires a different size input. Then the VHDL description has to be modifiedsignificantly, since the range of the vector affects many places in the description. Theinformation is not concentrated, and there are many dependencies. Attributes can resolve thesedependencies.

Here is an improved version of the same example, where attributes LEFT, RIGHT, and RANGE

define the dependencies on the size of the vector.

entity masked_parity isport ( source : in bit_vector (5 downto 0) ;

mask : in bit_vector (5 downto 0) ;result : out bit

) ;end masked_parity ;

architecture soso of masked_parity isbegin

process (source, mask)variable tmp : bit ;variable masked_source : bit_vector (5 downto 0) ;

beginmasked_source := source and mask ;tmp := masked_source(0) ;for i in 1 to 5 loop

tmp := tmp XOR masked_source(i) ;end loop ;result <= tmp ;

end process ;end soso ;

entity masked_parity isgeneric ( size : integer := 5) ;

port ( source : in bit_vector (size downto 0) ;mask : in bit_vector (source’RANGE) ;result : out bit

) ;end masked_parity ;

architecture better of masked_parity isbegin

process (source, mask)variable tmp : bit ;variable masked_source : bit_vector (source’RANGE) ;

Page 47: PrecisionRTL Style

VHDL Language FeaturesBlocks

Precision Synthesis Style Guide, 2011a Update2 47November 2011

If the application requires a different size parity checker, this time we only have to modify thesource vector range, and the attributes ensure that the rest of the description gets adjustedaccordingly. Now the information is concentrated.

BlocksWhen using processes and dataflow statements it is possible to use VHDL as a high levelhardware description language. However, as the descriptions get more and more complicated,some form of design partitioning, or hierarchy, is required or desirable.

VHDL offers a variety of methods for design partitioning. One form of partitioning is to dividea description into various processes. In the following sections four more forms of partitioningare discussed: blocks, subprograms (functions and procedures), components and packages.

A block is a method to cluster a set of related dataflow statements. Signals, subprograms,attributes, etc. that are local to the block can be defined in a block declarative region. Allstatements in a block are executed concurrently, and thus define a dataflow environment.

beginmasked_source := source and mask ;tmp := masked_source(source’LEFT) ;for i in source’LEFT+1 to source’RIGHT loop

tmp := tmp xor masked_source(i) ;end loop ;result <= tmp ;

end process ;

end better ;

architecture xxx of yyy issignal global_sig ,g1,g2,c bit ;

beginB1 : block -- block declarative region

signal local_sig : bit ;begin -- block concurrent statements

local_sig <= global_sig ;-- Block in a block

B2 : block (c=’1’) -- Block has “GUARD” expressionport (o1,o2 : out bit)-- Block port declarationsport map (o1=>g1,o2=>g2) ;

begino1 <= guarded local_sig ;o2 <= global_sig ;

end block ;end block ;

end xxx ;

Page 48: PrecisionRTL Style

Precision Synthesis Style Guide, 2011a Update248

VHDL Language FeaturesFunctions and Procedures

November 2011

Blocks can be nested, for example.

Signals, ports and generics declared outside the block can be used inside the block, eitherdirectly (as global_sig is used in block B2), or via a port map (as g1 is connected to o1 inblock B2) or generic maps (for generics). There is no real difference between the two methods,except that the port (generic) map construct is a cleaner coding style which could reduce errorswhen using or assigning to global objects.

A block can also have a GUARD expression (c=’1’ in block B2). In that case, an assignmentinside the block that contains the keyword GUARDED will only be executed when the GUARD

expression is TRUE. In the example, o1 only gets the value of local_sig when c=’1’. GUARDEDblocks and assignments provide a interesting alternative to construct latches or flip-flops in thesynthesized circuit. For examples, refer to “Registers” on page 205.

Precision RTL Synthesis fully support blocks, with port/generic lists and port/generic maps andthe GUARD options of blocks.

Functions and ProceduresSubprograms (function and procedures) are powerful tools to implement functionality that isrepeatedly used. Functions take a number of arguments that are all inputs to the function, andreturn a single value. Procedures take a number of arguments that can be inputs, outputs orinouts, depending on the direction of the flow of information through the argument. Allstatements in functions and procedures are executed sequentially, as in a process. Also,variables that are local to the subprogram can be declared in the subprogram. Local signals arenot allowed.

As an example, suppose you would like to add two vectors. In this case, you could define afunction that performs the addition. The following code fragment shows how an addition of two6-bit vectors is done.

function vector_adder (x : bit_vector(5 downto 0);y : bit_vector(5 downto 0)) return bit_vector(5 downto 0) is

-- declarative regionvariable carry : bit ;variable result : bit_vector(5 downto 0) ;

begin-- sequential statements

carry := ’0’ ;for i in 0 to 5 loop

result (i) := x(i) xor y(i) xor carry ;carry := carry AND (x(i) OR y(i)) OR x(i) AND y(i) ;

end loop ;return result ;

end vector_adder ;

Page 49: PrecisionRTL Style

VHDL Language FeaturesFunctions and Procedures

Precision Synthesis Style Guide, 2011a Update2 49November 2011

That vector addition, implemented this way, is not very efficient for synthesis. The packagesexemplar and exemplar_1164 provide vector additions that can implement efficient/fast addersmore easily.

An example of a procedure is shown. The procedure increments a vector only if an enable signalis high.

This incrementer procedure shows the behavior of an in/out port. The parameter vect is both setand used in this procedure. Also, the procedure statements use a call to the previously definedvector_adder function. If an input of a function or a procedure is not connected when it isused, that input will get the initial value as declared on the interface list.

For example, input ena will get (initial) value ’1’ if it is not connected in a procedure call to theprocedure increment. It is an error if an input is not connected and also does not have an initialvalue specified.

One important feature of subprograms in VHDL is that the arguments can be unbound. Thegiven examples operate on vectors of 6 bits. If you want to use the subprograms for arbitrarylength vectors, you could specify the length-dependencies with attributes and not specify arange on the parameters (leave them unbound). Here is a redefinition of both the vector additionfunction and the incrementer procedure for arbitrary length vectors.

procedure increment ( vect : inout bit_vector(5 downto 0);ena : in bit :=’1’) is

beginif (ena=’1’) then

vect := vector_adder (vect, "000001") ;end if ;

end increment ;

function vector_adder (x : bit_vector; y : bit_vector) return bit_vectoris

variable carry : bit := ’0’ ;variable result : bit_vector(x’RANGE) ;

beginfor i in x’RANGE loop

result (i) := x(i) XOR y(i) XOR carry ;carry := carry AND (x(i) OR y(i)) OR x(i) AND y(i) ;

end loop ;return result ;

end vector_adder ;

procedure increment (vect : inout bit_vector; ena : in bit :=’1’) isbegin

if (ena=’1’) thenvect := vector_adder (x=>vect, "000001" ) ;

end if ;end increment ;

Page 50: PrecisionRTL Style

Precision Synthesis Style Guide, 2011a Update250

VHDL Language FeaturesResolution Functions

November 2011

In the procedure increment example, name association was added in the parameter list of thevector_adder call. The name association (e.g., x=>vect) is an alternative way to connect aformal parameter (x) to its actual parameter (vect). Name associations (as well as positionalassociations) are helpful if the number of parameters is large.

Subprograms can be called from the dataflow environment and from any sequentialenvironment (processes and other sub-programs). If a procedure output or inout is a signal, thecorresponding parameter of the procedure should also be declared as a signal.

Subprograms can be overloaded. That is, there could be multiple subprograms with the samename, but with different parameter list types or return types. Precision RTL Synthesis performsthe overlaod resolution.

In the last example, the variable carry was initialized in when it was declared. This is a morecompact way of setting the starting value of a variable in a function or procedure. The initialvalue does not have to be a constant. It could be a nonconstant value also (like the value of oneof the parameters).

Precision RTL Synthesis fully supports all VHDL language features of functions andprocedures.

Resolution Functions

Syntax and SemanticsIn a concurrent area in VHDL, all statements happen concurrently. That means that if there aretwo assignments to the same signal, then the final value of the signal needs to be resolved. InVHDL, you can only have multiple concurrent assignments to a signal if the type of the signal isresolved. A resolved type is a type with a resolution function. A good example of a resolvedtype is the type std_logic from the IEEE 1164 package:

subtype std_logic is resolved std_ulogic ;

Page 51: PrecisionRTL Style

VHDL Language FeaturesResolution Functions

Precision Synthesis Style Guide, 2011a Update2 51November 2011

The word resolved in this declaration refers to a resolution function called resolved. Here ishow it is specified in the std_logic_1164 package:

The resolution function of type std_logic takes a vector of the (unresolved) base-type ofstd_logic : std_ulogic. It returns a single std_ulogic.

Now if you have two concurrent assignments to any signal of type std_logic, the resolutionfunction will be called to determine the final value of the signal. The resolution function will becalled with a vector with two elements, where each element contains the value of a concurrentassignment. Inside the resolution function, the final value of the signal is defined, based on thetwo assignment values.

Synthesis IssuesResolution functions are especially useful when you want to model nets with multiple drivers(like buses with three-state drivers). However, VHDL lets you define a resolution functionfreely, without any special restrictions. The resolution function is thus just another function,only it gets called wherever there are multiple assignments to a signal of the (sub) type it isattached to.

You can define a resolution function and attach it to a subtype, and Precision RTL Synthesiswill synthesize the circuitry it implies for each multiple assignment.

In many cases, the resolution function mimics a certain electrical behavior for the simulator. Inthe case of the IEEE type std_logic, and its resolution function resolved, the resolutionfunction resembles tri-states being wired together. Therefore, the synthesis directive attribute(synthesis_result) is set to WIRED_THREE_STATE.

This synthesis directive is a hint to Precision RTL Synthesis to interpret the elements of theincoming vector as parallel three-state assignments, where the three-state condition is derivedfrom the assignment. That way, any three-state drivers can be created with multipleassignments.

function resolved ( s : std_ulogic_vector ) return std_ulogic isvariable result : std_ulogic := ’Z’; -- weakest state defaultattribute synthesis_return of result:variable is “WIRED_THREE_STATE” ;begin

-- the test for a single driver is essential otherwise the-- loop would return ’X’ for a single driver of ’-’ and that-- would conflict with the value of a single driver unresolved-- signal.if (s’LENGTH = 1) then return s(s’LOW);else for i in s’range loop result := resolution_table(result, s(i)); end loop;end if return result;

end resolved;

Page 52: PrecisionRTL Style

Precision Synthesis Style Guide, 2011a Update252

VHDL Language FeaturesResolution Functions

November 2011

Let’s go through one example step by step, to show what the resolution function is doing:

When the example is executed, Precision RTL Synthesis will give the following error:

This message is obvious, since you did not explain what should happen when a and b force(different) values concurrently onto signal TMP. For that, write a resolution function. Supposeyou want the concurrent assignments to be ANDed. Then you should write a resolution functionthat performs an AND operation of the elements of its input vector.

Also attach the resolution function to TMP. You could do that in two ways:

1. Create a subtype of bit, say, rbit, and attach the resolution function to that subtype,just as we did for the type std_logic.

2. Directly attach the resolution function to the signal TMP. This is the easiest way, and it isuseful if there are not many signals that need the resolution function.

The second method is:

entity test_resolver isport (a, b : bit ;

o : out bit ) ;end test_resolver ;architecture rtl of test_resolver is

signal tmp : bit ;begin

tmp <= a ;tmp <= b ;o <= tmp ;

end rtl ;

Error, multiple sources on unresolved signal TMP; also line 10.

entity test_resolver isport (a, b : bit ;

o : out bit ) ;end test_resolver ;

architecture rtl of test_resolver is-- Write the resolution function that ANDs the elements:

function my_and_resolved (a : bit_vector) return bit isvariable result : bit := ’1’ ;

Page 53: PrecisionRTL Style

VHDL Language FeaturesComponent Instantiation

Precision Synthesis Style Guide, 2011a Update2 53November 2011

Precision RTL Synthesis will synthesize this description and tmp becomes the AND of a and b.

Component InstantiationComponents are a method of introducing structure in a VHDL description. A componentrepresents a structural module in the design. Using components, it is possible to describe anetlist in VHDL. Components are instantiated in the dataflow environment. Here is an exampleof a structural VHDL description where four one-bit rams and a counter module areinstantiated.

beginfor i in a’range loop

result := result AND a(i) ;end loop ;return result ;

end my_and_resolved ;

-- Declare the signal and attach the resolution function to it:signal tmp : my_and_resolved bit ;

begintmp <= a ;tmp <= b ;o <= tmp ;

end rtl ;

entity scanner isport ( reset : in bit ;

stop : in bit ;load : in bit ;clk : in bit ;load_value : in bit_vector (3 downto 0) ;data : out bit_vector (3 downto 0)

) ;end scanner ;

architecture rtl of scanner is

component RAM_32x1port ( a0, a1, a2, a3, a4 : in bit ;

we, d : in bit ; o : out bit

) ;end component ;

Page 54: PrecisionRTL Style

Precision Synthesis Style Guide, 2011a Update254

VHDL Language FeaturesComponent Instantiation

November 2011

The generate statement is used here to instantiate the four RAMs.

Components have to be declared before they can be used. This is done in the declaration area ofthe architecture, or in a package (see next section). The declaration defines the interface of thecomponent ports with their type and their direction. Actually this example is just a netlist ofcomponents. We added one dataflow statement (the assignment to ena) to show that structureand behavior can be mixed in VHDL.

The ports of the component are connected to actual signals (or ports) with the port mapconstruct. The generics of the component are connected to actual values with the generic mapconstruct. In this example the generic size is set to 4 with the attribute length on the array addr.If no generic value was set to size (or if the generic map construct was completely absent),size gets value 4, as indicated by the initial value on size in the generic list of the component.It is an error if a generic (or input port) is not connected in a generic map (or port map) constructand there is no initial value given in the component generic (or port) list.

In the example, the input ports of the component RAM_32x1 are individual bits (a0, a1, a2, a3,a4). If the input would have been declared as a bit_vector (0 to 4), then the individual bitscould be connected with indexed formal names:

component countergeneric (size : integer := 4 ) ;port ( clk : in bit ;

enable : in bit ; reset : in bit ; result : out bit_vector (4 downto 0)

) ;end component ;

signal ena : bit ;signal addr : bit_vector (4 downto 0) ;

beginfor i in 0 to 3 generate

ram : RAM_32x1 port map (a0=>addr(0), a1=>addr(1),a2=>addr(2), a3=>addr(3), a4=>addr(4), d=>data(i),we=>load, o=>data(i) ) ;

end generate ;

ena <= not stop ;count : counter generic map (size=>addr’length)

port map(clk=>clk, enable=>ena, reset=>reset, result=>addr) ;

end rtl ;

.. port map (a(0) => addr(0), a(1) => addr(1), a(2) => addr(2), a(3) => addr(3), a(4) => addr(4), ...

Page 55: PrecisionRTL Style

VHDL Language FeaturesBinding a Component

Precision Synthesis Style Guide, 2011a Update2 55November 2011

or with a sliced formal name:

or simply with a full identifier association:

Precision RTL Synthesis supports any form of slicing or indexing of formal parameter names,as long as the VHDL language rules are obeyed (formal name should be static).

Precision RTL Synthesis also supports type-transformation functions in port and genericassociations as long as they are synthesizable. Type transformation functions are not very oftenused and so are not explained here.

Binding a ComponentThe definition of the components counter and RAM_32x1 are not yet given in the example. Theprocess of giving a contents definition for a component is called binding in VHDL. WithPrecision RTL Synthesis, there are four ways to do component binding:

1. Specify an entity with the same name as the component and an architecture for it. Thisway, the component gets bound to the entity with the same name. This is called ’defaultbinding’ in VHDL.

2. Specify a configuration specification. Here you can bind a component to an entity with adifferent name, and you can even connect component ports to entity ports with adifferent name.

3. Use a source technology in Precision RTL Synthesis that contains a cell with the samename as the component. Precision RTL Synthesis will bind the component to thetechnology cell (and include functional, timing and area information for it).

4. Do not specify any entity for the component. This way, Precision RTL Synthesis willissue a warning and create a black-box for the component.

.. port map (a(0 to 4) => addr(0 to 4), .....

.. port map ( a => addr, .....

Page 56: PrecisionRTL Style

Precision Synthesis Style Guide, 2011a Update256

VHDL Language FeaturesBinding a Component

November 2011

Option 1 - Using a Default BindingThe component counter is a good example of the first option:

This description only includes behavior. There is no component instantiated, although it ispossible, and it makes hierarchical design possible.

Note that in this case the overloaded ’+’ operator is used on vectors, as defined in the exemplarpackage. Also note that an asynchronous reset construction is used to reset the counter value.

Option 2 - Using a Configuration SpecificationThe second option gives more freedom to bind an entity to a component. Suppose you have acounter entity that does exactly what you need, but it is named differently, and (or) hasdifferently named ports and generics:

entity counter isgeneric (size : integer ) ;port ( clk : in bit ;

enable : in bit ;reset : in bit ;result : out bit_vector (size-1 downto 0)) ;

end counter ;

architecture rtl of counter isbegin

process (clk,reset)begin

if (reset=’1’) thenresult <= (others=>’0’) ;

elsif (clk’event and clk=’1’) thenif (enable=’1’) then

result <= result + "1" ;end if ;

end if ;end process ;

end rtl ;

entity alternative is generic (N : integer) ; port (clock : in bit ; ena : bit : reset : bit ; output : out bit_vector (N-1 downto 0)

) ; end alternative ; architecture ex of alternative is begin ..... end ex ;

Page 57: PrecisionRTL Style

VHDL Language FeaturesBinding a Component

Precision Synthesis Style Guide, 2011a Update2 57November 2011

The following example configuration specification could be used to bind the componentcounter to the entity alternative, for a particular or all instances of the counter component.The configuration specification is added after the counter component declaration:

This configuration specification binds all instances of component counter to an entity calledalternative (architecture ex) in the work library, and it connects the generics and ports of theentity to differently named generics and ports in the component. If the ports and generics havethe same name in the entity and the architecture, the generic map and port map don’t have to begiven. If there is only one architecture of the entity alternative then the architecture (ex) doesnot have to be given either. If not all, but just one or two instances of the component countershould be bound to the entity alternative, then replace all by a list of instance (label) names.

Configuration specifications are a very powerful method to quickly switch definitions ofcomponents to a different alternative.

The tool fully supports all forms of configuration specifications that are allowed in thelanguage.

If no configuration specification is given, the synthesis tools use the default binding asexplained in the first option.

Option 3 - Matching a Component Name to a Library CellIn the third option, if you use a component name that matches the name of a cell in the targettechnology library, then that cell will be instantiated in the design. In this case, assume that thename RAM_32x1 is the name of a RAM cell in the target technology library.

Option 4 - Creating a Black Box by Omitting the EntityThe fourth option is to omit declaring an entity for the component. This is helpful whenhierarchy has to be preserved. This technique can be effectively used to maintain hierarchy.Precision RTL Synthesis generates an empty module for each component it cannot find in thepresent file as an entity or as a library cell in the source technology. Empty modules show up asblocks in the final netlist. They are not touched by the synthesis and optimization process.Components without a definition can also help to isolate a particular difficult or user-defined

component counter generic (size : integer) ; port (clk : in bit ; enable : in bit ; reset : in bit ; result : out bit_vector(4 downto 0)

) ;end component counter ;for all:counter use entity work.alternative(ex) generic map (N=>size) port map (clock=>clk, ena=>enable, reset=>reset,output=>result) ;

Page 58: PrecisionRTL Style

Precision Synthesis Style Guide, 2011a Update258

VHDL Language FeaturesBinding a Component

November 2011

part of the design from the synthesis operations. Clock generators or other asynchronouscircuits or time-critical user-defined modules are an example of this.

Finding Definitions of ComponentsIn order to instantiate an entity into a VHDL description, you must first declare a component forit. If you use a component instantiation in your VHDL design, Precision RTL Synthesis tries tofind the definition of that component. There are three possibilities.

1. The component is a cell in a source technology library.

2. The component has a matching (named) entity in the VHDL source

3. The component has no definition.

If a source technology is specified, then the component in the source technology library issearched for. This is especially helpful if the component represents a particular macro in thesource technology.

If the component is not present in the source technology, Precision RTL Synthesis tries to findan entity and architecture for it. The entity (and architecture) could be present in the same file,or in an included VHDL file.

If Precision RTL Synthesis cannot find a matching entity for the component, then the contentsof the component are undefined, and the following warning is issued:

Working with components without a definition can be useful if a particular module of the designis not synthesizable. A clock generator or a delay-module is an example of this. The contents ofthat module should be provided separately to the physical implementation tools. Leavingcomponents undefined is also useful in two other cases:

1. To preserve hierarchy through the synthesis process.

2. For using hard and soft macros in the target technology.

It is possible to explicitly leave the contents of a component empty, even though there is aentity/architecture for it or a cell in the source technology library. In this case, you shouldspecify the boolean attribute dont_touch on the component, or on the corresponding entity.

Warning, component component_name has no definition

Page 59: PrecisionRTL Style

VHDL Language FeaturesPackages

Precision Synthesis Style Guide, 2011a Update2 59November 2011

This can be useful when only a part of the hierarchy of a design has to be synthesized or if auser-defined simulatable but not synthesizable block is run through Precision RTL Synthesis.Here is an example of how to set the dont_touch attribute:

You can apply dont_touch to a particular instance of a component by setting this attribute onthe label of the component instantiation statement. This has the same effect as if the attributewere added to the underlying entity.

PackagesA package is a cluster of declarations and definitions of objects, functions, procedures,components, attributes etc. that can be used in a VHDL description. You cannot define an entityor architecture in a package, so a package by itself does not represent a circuit.

A package consists of two parts. The package header, with declarations, and the package body,with definitions. An example of a package is std_logic_1164, the IEEE 1164 logic typespackage. It defines types and operations on types for 9-valued logic.

To include functionality from a package into a VHDL description, the use clause is used.

This example shows how the IEEE 1164 standard logic types and functions become accessibleto the description in entity xxx.

This is the general form to include a package in a VHDL description:

The use clause is preceded by a library clause. The predefined libraries work and std do nothave to be declared in a library clause before they are used in a use clause. All other librariesdo need to be declared.

component clock_gen.....

end component ;attribute dont_touch : boolean ;attribute dont_touch of clock_gen:component is true ;

library ieee ;use ieee.std_logic_1164.all ;

entity xxx isport ( x : std_logic ; -- type std_logic is known since it is

-- defined in package-- std_logic_1164

...

library lib ;use lib.package.selection ;

Page 60: PrecisionRTL Style

Precision Synthesis Style Guide, 2011a Update260

VHDL Language FeaturesPackages

November 2011

The selection can consist of only one name of a object, component, type or subprogram that ispresent in the package, or the word all, in which case all functionality defined in the package isloaded into Precision RTL Synthesis, and can be used in the VHDL description.

How to Use PackagesA functionality described in a VHDL package is included into the VHDL design using the useclause. This is the general form of the use clause:

The use clause is preceded by a library clause. There are predefined libraries work and std

that do not have to be declared in a library clause before they are used in a use clause. Allother libraries need the top to be declared. Library std is normally only used to includepackages predefined in VHDL1076, but library work is free to be used for any user-definedpackages. User-defined library names are also allowed.

Precision searches for packages in the library specified by the use statement. If automap_workis enabled, Precision searches the library work for the package instead. If the package cannot befound, Precision issues an error message.

The selection can consist of only one name of an object, component, type or subprogram that ispresent in the package, or the word all, in which case all functionality defined in the package isused in the VHDL description.

library ieee;use ieee.std_logic_1164.all;package global_decl istype log_arr is array(std_logic) of std_logic;constant std_to_bin : log_arr:=('X','X','0','1','X','X','0','1','X');function to_bin (from : std_logic) return std_logic;

end;

library ieee;use ieee.std_logic_1164.all;use work.global_decl.all;package body global_decl isfunction to_bin (from : std_logic) return std_logic isbeginreturn std_to_bin(from);end ;

end package body;

library lib ;use lib.package.selection ;

Page 61: PrecisionRTL Style

VHDL Language FeaturesAliases

Precision Synthesis Style Guide, 2011a Update2 61November 2011

As an example, the IEEE 1164 std_logic_1164 package (that defines the multi-valued logictypes that are often used for circuit design), is included with the following statements:

This package is loaded from the file:<precision install directory>/pkgs/techdata/vhdl/ex_ii64.vhd.

This file contains only the declarations of the functions of the std_logic_1164 package. Thebodies of the functions are built into Precision RTL Synthesis for synthesis efficiency.

The contents of the package you include with a use clause becomes visible and is usable onlywithin the scope where you use the use clause. The VHDL scoping rules are not explained inthis manual. However, if you start a new entity (and architecture), always make sure that youinclude the packages you need with use clauses just before the entity.

AliasesAn alias is an alternate name for an existing object. By using an alias of an object, you actuallyuse the object to which it refers. By assigning to an alias, you actually assign to the object towhich the alias refers.

Aliases are often useful in unbound function calls. For instance, if you want to make a functionthat takes the AND operation of the two left most bits of an arbitrary array parameter. If you wantto make the function general enough to handle arbitrary sized arrays, this function could looklike this:

This function will only work correctly if the index range of arr is descending (downto).Otherwise, arr’left-1 is not a valid index number. VHDL does not have a simple attributethat will give the one-but-leftmost bit out of an arbitrary vector, so it will be difficult to make a

library ieee ;use ieee.std_logic_1164.all ;

signal vec : std_logic_vector (4 downto 0) ;alias mid_bit : std_logic is vec(2) ;-- Assignment :mid_bit <= ’0’ ;-- is the same asvec(2) <= ’0’ ;

function left_and (arr: std_logic_vector) return std_logic isbegin return arr(arr’left) and arr(arr’left-1) ;end left_and ; -- Function does not work for ascending index ranges of arr.

Page 62: PrecisionRTL Style

Precision Synthesis Style Guide, 2011a Update262

VHDL Language FeaturesSyntax and Semantic Restrictions

November 2011

function that works correctly both for ascending and descending index ranges. Instead, youcould make an alias of arr, with a known index range, and operate on the alias:

Precision RTL Synthesis fully supports aliases.

Syntax and Semantic RestrictionsVHDL as the IEEE Standard 1076 is a extended language with many constructs that are usefulfor simulation. However, during the initial development of the language, logic synthesis was nottaken into account. Therefore, a number of constructs or combination of constructs cannot beimplemented in actual circuits. VHDL 1076 is fully simulatable, but not fully synthesizable.

Synthesis Tool RestrictionsThis section discusses the syntax and semantic restrictions of the VHDL parsers of PrecisionRTL Synthesis.

• Operations on files not supported. Files in VHDL could behave like ROMs or RAMs,but Precision RTL Synthesis does not support using file (types), and will ignore, butaccept, file (type) declarations.

• Operations on objects of real types are not supported. Objects of real types have nodefined bit-resolution. Precision RTL Synthesis ignores, but accepts declarations of(objects of) real types.

• Operations on objects of access types are not supported, since they lead tounsynthesizable behavior. Precision RTL Synthesis ignores, but accepts declarations of(objects of) access types.

• Attributes BEHAVIOR, STRUCTURE, LAST_EVENT, LAST_ACTIVE, and TRANSACTION are notsupported.

• Global, non-constant signals, that is, signals declared in a package, are supported. Thefollowing limitations apply to such signals.

o Attributes such as ALLOW_INIT_VAL are ignored.

o Memory cannot be inferred for such signals.

function left_and (arr : std_logic_vector) return std_logic isalias aliased_arr : std_logic_vector (0 to arr’length-1) is arr ;

beginreturn aliased_arr(0) and aliased_arr(1) ;

end left_and ;-- Function works for both ascending and descending index-- ranges of arr.

Page 63: PrecisionRTL Style

VHDL Language FeaturesSyntax and Semantic Restrictions

Precision Synthesis Style Guide, 2011a Update2 63November 2011

• Allocators are not supported, because they perform dynamic allocation of resources,which is not synthesizable.

• Resolution functions with a synthesis directive are allowed.

VHDL Language RestrictionsApart from these restrictions, which are mostly tool-related, there are some basic restrictionsthat apply to VHDL descriptions for synthesis. Since they occur quite often, additionaldescriptions are presented here to clarify the problems involved for synthesis. Here is the list:

• after clause ignored.

• Restrictions on Initialization values.

• Loop restrictions

• Restrictions on edge-detecting attributes (EVENT and STABLE).

• Restrictions on wait statements.

• Restrictions on multiple drivers on one signal.

A more detailed description of these restrictions follows below:

After Clause IgnoredThe after clause refers to delay in a signal. Since delay values cannot be guaranteed insynthesis, they are ignored by the synthesis tools.

Restrictions on Initialization ValuesInitialization values are allowed in a number of constructs in VHDL:

1. Initial value of a signal in a signal declaration.

2. Initial value of a variable in a variable declaration in a process.

3. Initial value of a variable in a variable declaration in a subprogram (procedure orfunction).

4. Initial value of a generic or port in a component declaration.

5. Initial value of a parameter in a subprogram interface list.

The problem with initialization values for synthesis is that some initial values define the initialvalue of an object before actual simulation is done. This behavior corresponds to controlling thepower-up state of a device that would be synthesized from the VHDL description. Sincesynthesis cannot control the power-up state of a device, this kind of initial value cannot besynthesized. However, if after initialization there is never an change of value, the behavior canbe synthesized, and resembles a simple constant value.

Page 64: PrecisionRTL Style

Precision Synthesis Style Guide, 2011a Update264

VHDL Language FeaturesSyntax and Semantic Restrictions

November 2011

Precision RTL Synthesis fully supports initialization values, except for initializing objects thatcan change their value after initialization. That is, the following form of initialization values areNOT supported because they imply power-up behavior of the synthesized device:

1. Initial values of a signal in a signal declaration.

2. Initial value of a variable in a variable declaration in a process.

3. Initial value of an OUTPUT or INOUT port in an interface list.

All other forms of initialization values are supported by the synthesis tools.

Loop RestrictionsLoops are supported if they are bound by constants or they have wait until statements toprevent combinational loops.

Restrictions On Edge-Detecting Attributes ('event)Most restrictions on VHDL to assure correct compilation into a logic circuit are on theconstructs that define edges or changes on signals. The ’EVENT attribute is the best example ofthis. signal’EVENT is TRUE only if signal changes. Then it is TRUE for one simulation delta oftime. In all other cases it is FALSE. The STABLE attribute is the boolean inversion of EVENT.

There are two restrictions for synthesis on usage of the EVENT and the STABLE attribute:

1. An EVENT or STABLE attribute can be used only to specify a leading or falling clock edge.For example:

2. Clock edge expressions can only be used as conditions. For example:

These restrictions originate from the fact that binary logic circuits have a restricted number ofelements that are active ONLY during signal edges. Basically, only (set/resettable) edgetriggered flip-flops show that behavior. Within these restrictions, Precision RTL Synthesis

clk’event and clk=’1’ -- Leading edge of clkclk’event and clk=’0’ -- Falling edge of clkNOT clk’stable and clk=’0’ -- Falling edge of clkclk’event and clk -- Leading edge of (boolean) clk

if (clk’event and clk=’1’) then ...wait until NOT clk’stable and clk=’0’ ;wait until clk=’1’ ; --Implicit clock edge due to

--VHDL semantics of ’wait’block (clk’event and clk=’1’... --Block GUARD condition

Page 65: PrecisionRTL Style

VHDL Language FeaturesSyntax and Semantic Restrictions

Precision Synthesis Style Guide, 2011a Update2 65November 2011

allows free usage of the clock edge conditions, either in guarded blocks, processes orsubprograms.

Restrictions on Wait StatementsAll state-of-the-art VHDL synthesis tools on the market right now have strong restrictions withrespect to wait statements and use of edge-detecting attributes ( 'event and 'stable). Here arethe (informal) restrictions for the wait statement:

• Multiple wait statements are supported in a process with some synthesis restrictions.All the control paths should have at least one wait statement and all of the wait

statements should be identical with a single bit clock expression.

• The expression in the until condition must specify a leading or falling single clockedge. (Examples are shown above in the EVENT attribute section.)

All assignments inside the process result in the creation of registers. Each register (flip-flop) isclocked with the single clock signal.

There are a number of cases where multiple waits are synthesizable and resemble state-machine behavior. In Precision RTL Synthesis, multiple waits are supported.

Restrictions on Multiple Drivers on One SignalVHDL does not allow multiple drivers on a signal of an unresolved type. For signals of resolvedtypes, VHDL defines that a (user-defined) resolution function defines what the signal value isgoing to be in case there are multiple driver (simultaneous assignments) to the signal.

A resolution function with meta-logical values (’Z’, ’X’, etc.) in general leads to behavior thatis not synthesizable (since logic circuits cannot produce meta-logical values). Therefore, ingeneral, VHDL synthesis tools do not allow multiple drivers on a signal. However, if theresolution function defines the behavior of multiple three-state drivers on a bus, multiple driversof a signal could represent synthesizable behavior.

The ’Z’ value is in general used to identify three-state behavior. The resolution function of theIEEE std_logic (resolved) type is written so that multiple drivers on a signal of std_logic doresemble multiple three-state drivers on a bus. Therefore, the synthesis tools accept multipleassignments to the same signal as long as each assignment is conditionally set to the ’Z’ value.The synthesis tools allow free usage of ’Z’ assignments (either from dataflow statements,process statements or from within procedures). Precision RTL Synthesis implements three-statedrivers to mimic the three-state behavior.

It is important to note that Precision RTL Synthesis does not check if there could be a bus-conflict on the driven bus. In this case, the simulation would just call the resolution functionagain to resolve the value (normally producing a meta-logical value), but the behavior forsynthesis is not defined. Avoiding bus conflicts is the responsibility of the user.

Page 66: PrecisionRTL Style

Precision Synthesis Style Guide, 2011a Update266

VHDL Language FeaturesSyntax and Semantic Restrictions

November 2011

Page 67: PrecisionRTL Style

Precision Synthesis Style Guide, 2011a Update2 67November 2011

Chapter 2VHDL 2008 Language Features

This section describes key VHDL 2008 Language Support features that are supported inPrecision Synthesis. These features include:

• Conditional and Selected Sequential Assignments

• Simplified Case Expression Support

• Unconstrained Element Support

• Context Declarations

• Extensions to Generate

• Fixed Point Package

• Expressions Port Map

• Read Out Ports

• Simplified Sensitivity List

• Block Comments

• Matching Case Statement

• Array-Scalar Operators

• Logical Reduction Operators

• Matching Relational Operators

• Conditional Operator Support

• Maximum and Minimum Function Support

• Unconstrained Record Elements

Conditional and Selected SequentialAssignments

VHDL 2008 allows conditional and selected signal assignment statements in concurrent(signals only) and sequential (signals and variables) modes. Prior to VHDL-2008, this waslimited to conditional and selected signal assignments in concurrent context only. A conditionalstatement (when?) carries the same semantics as an if-else-if statement. A select statement(select?) carries the same semantics as a case (case?) statement. By extending support for

Page 68: PrecisionRTL Style

Precision Synthesis Style Guide, 2011a Update268

VHDL 2008 Language FeaturesSimplified Case Expression Support

November 2011

these conditional and select statements for variables and signals and also in sequential mode, thesemantics of the language are made consistent. Thus, the choice list in a selected expression caneven contain don’t-cares (-) when the select? usage is done. The following example describesthis clearly.

Example

Simplified Case Expression SupportAfter associating values ‘1’ and ‘0’ to the first and second elements in an array for a caseexpression, other elements can be assigned to value ‘1’ provided the case expression is locallystatic. Prior to VHDL 2008, assigning values to elements after the first and second assignmentswas not possible. Thus, the following examples are now valid with VHDL 2008.

VHDL 2002 VHDL 2008

Process (d, reset)Begin If reset = '1' then Q <= '0' Else Q <= d; End if;End Process;

Process (reset, d)Begin Q <= '0' when reset elsed;End process;

Process (val1, val2, val3,val4, sel)Begin Case sel is When "00" => q <= val1; When "01" => q <= val2; When "10" => q <= val3; When "11" => q <= val4; End case;End process;

Process (val1, val2, val3,val4, sel)Beginwith sel select q <= val1when "00",val2 when "01",val3 when "10",val4 when "11";end process;

Page 69: PrecisionRTL Style

VHDL 2008 Language FeaturesUnconstrained Element Support

Precision Synthesis Style Guide, 2011a Update2 69November 2011

Example

Unconstrained Element SupportVHDL 2008 allows array elements to be unconstrained. It is not necessary to define an array’ssize and this can instead be determined during signal/variable/constant declaration duringelaboration. The keyword open can be used to skip constraints during declaration.

Example

Type M_unconstrained is array (natural range<>, natural range <>) of bit;Type A_unconstrained is array (character range<>) of M_unconstrained;Type A1_partially_constrained is array (character range 'a' to 'z') ofM_unconstrained;Subtype s4 is A_unconstrained(open)(0 to 7, 31 downto 16);

NoteSupport for unconstrained elements currently exists only for arrays and not for records.

Context DeclarationsIn VHDL 2008, you can create context declarations of your libraries and ‘use’ clauses.

Example

VHDL 2002 VHDL 2008

Variable s: bit_vector (3downto 0);Variable c: bit;Subtype bv5 is bit_vector(4downto 0 );….Case (bv5'(s &c))When "00000" => …When "00001" => ….When others => ….End case

Variable s: bit_vector (3downto 0);Variable c: bit; ….Case (s &c)When "00000" => …When "00001" => ….When others => ….End case

Variable s: bit_vector( 3downto 0);….Case (s)When "0001" => …When "0010" => ….When others => ….End case

Variable s: bit_vector( 3downto 0);….Case (s)When (0 => '1' others =>'0') => …When (1 => '1' others =>'0') => ….When others => ….End case

Page 70: PrecisionRTL Style

Precision Synthesis Style Guide, 2011a Update270

VHDL 2008 Language FeaturesContext Declarations

November 2011

context widget_context islibrary IEEE;use IEEE.std_logic_1164.all, IEEE.numeric_std.all;use widget_lib.widget_defs.all;use widget_lib.widget_comps.all;end context widget_context;...........library widget_lib;context widget_lib.widget_context;

Page 71: PrecisionRTL Style

VHDL 2008 Language FeaturesExtensions to Generate

Precision Synthesis Style Guide, 2011a Update2 71November 2011

Extensions to GenerateVHDL 2008 introduces support for if-else-if and case generate statements. Previously, thegenerate feature was restricted to the if statement only.

Example

Fixed Point PackageVHDL 2008 adds support for Fixed Point Package which provides a representation of floatingnumbers in the form of fixed point representation. The types supported in fixed point packageare ufixed (unsigned fixed point) and sfixed (signed fixed point) types. These types are alwayssupposed to have “downto” ranges with positive ranges for integral part and negative ranges forfractional part. This is very useful for DSP applications. Annex G of the LRM 1076-2008contains more information about the usage of this package.

Example

6.5 is represented as

signal y: ufixed(4 downto -5);…....Y <= “0011010000”; -- 6.5

Also, since package generics are not supported currently, support for fixed_generic_pkg doesnot exist currently.

VHDL 2002 VHDL 2008

for I in width -1 downto 0generatebegin if I = width - 1 generate

adder_1: adder(in1, in2,out1); end generate

if not I = width - 1generate adder_2:adder(in3[i],in2[i], out2); end generateend generate

for I in width -1 downto 0generatebegin if I = width - 1 generate

adder_1: adder(in1, in2,out1); else generate adder_2:adder(in3[i],in2[i], out2); end generateend generate

Page 72: PrecisionRTL Style

Precision Synthesis Style Guide, 2011a Update272

VHDL 2008 Language FeaturesExpressions Port Map

November 2011

Expressions Port MapVHDL 2008 allows input ports to be connected to expressions instead of the need to createtemporary signals.

Example

Inst1 : trial_ent port map (cin1 => CONV_INTEGER(STD_LOGIC_VECTOR(tdin1)or x"1010") , cin2 => tdin2, cout1 => tdout1);

Read Out PortsVHDL 2008 allows output ports to be read. Though this feature is mainly intended to help theverification of assertions and monitors, language semantics do not stop it from being used inalgorithmic behavior.

The scope of this feature will support reading output port in architectures, sub-programs etc. Incase of variables in sub-programs, the value propagation won't be done as per LRM but in caseof signals the connection will be as passed by reference.

VHDL 2002 VHDL 2008

Entity dff is Port (clk, d: in bit; q,q_n: out bit);End entity;

Architecture rtl of dff isSignal q_int: bit;Begin Process (clk) Begin If (clk = '1') then q_int <= d; end if; end process; q <= q_int; q_n <= q_int;end rtl;

Entity dff is Port (clk, d: in bit; q,q_n: out bit);End entity;

Architecture rtl of dff isBegin Process (clk) Begin If (clk = '1') then q <= d; end if; end process; q_n <= q;end rtl;

Page 73: PrecisionRTL Style

VHDL 2008 Language FeaturesSimplified Sensitivity List

Precision Synthesis Style Guide, 2011a Update2 73November 2011

Simplified Sensitivity ListVHDL 2008 introduces the keyword 'all' which can be used in process sensitivity list. This willensure that all signals are appropriately added in the sensitivity list.

Example

Block CommentsVHDL 2008 introduces C-style multi-line comments starting with '/*' and ending with '*/'. Thenesting of block comments is, however, not allowed in VHDL 2008.

Example

VHDL 2002 VHDL 2008

Process(in1, in2, in3, in4)Begin Out1 <= in1; Out2 <= in2; Out3 <= in3; Out4 <= in4;End process

Process (all)Begin Out1 <= in1; Out2 <= in2; Out3 <= in3; Out4 <= in4;End process

VHDL 2002 VHDL 2008

Entity dff is Port (clk, d: in bit; q,q_n: out bit);End entity;

Architecture rtl of dff isSignal q_int: bit;Begin Process (clk)-- This line-- and this line-- must be commented Begin If (clk = '1') then q_int <= d; end if; end process; q <= q_int; q_n <= q_int;end rtl;

Entity dff is Port (clk, d: in bit; q,q_n: out bit);End entity;

Architecture rtl of dff isSignal q_int: bit;Begin Process (clk)/* This line and this line must be commented*/ Begin If (clk = '1') then q_int <= d; end if; end process; q <= q_int; q_n <= q_int;end rtl;

Page 74: PrecisionRTL Style

Precision Synthesis Style Guide, 2011a Update274

VHDL 2008 Language FeaturesMatching Case Statement

November 2011

Matching Case StatementIn VHDL 2008, case statements are introduced with Don't Care in the choice statement by usageof 'case?'. A simple example is described here where the value of the case expression Xin ismatched with expressions containing ‘don't care’. The restriction on Xin is that its value cannotcontain a '-' which is an error.

It is also an error if any two choice lists contain the same value. Therefore, the values "---1" and"--1-" in choice lists should yield an error due to an overlap of choices. The case expression isbit/std_ulogic or its vector.

Example

case? Xin is when "--1" => Zout <= Ain; when "-10" => Zout <= Bin;when others => Zout <= Cin;

Array-Scalar OperatorsArray Scalar Operators allow a scalar operand to be applied to all the elements of an array. Thearray-scalar logical operators are AND, OR, NAND, NOR, XOR and XNOR for bit, Booleanand std_ulogic types.

In the example shown here, the AND operator is applied to each bit of A with ASel and result isstored in T.

A : IN BIT_VECTOR (3 downto 0); ASel : In BIT; T <= A and ASel;

Page 75: PrecisionRTL Style

VHDL 2008 Language FeaturesLogical Reduction Operators

Precision Synthesis Style Guide, 2011a Update2 75November 2011

Logical Reduction OperatorsLogical Reduction Operators allow an array to be reduced to array element type by theapplication of the operator. The logical reduction operators AND, OR, NAND, NOR, XOR andXNOR are pre-defined for bit and Boolean vectors. They must be defined in std_logic_1164package for std_ulogic_vector and std_logic_vector.

The following is an example of parity bit calculation in both VHDL 2008 and VHDL 2002.

Matching Relational OperatorsVHDL 2008 introduces relational operators that return the result of the bit type or std_ulogictype instead of Boolean result. The matching relational operators are "?=", "?/=", "?<", "?<=","?>" and "?>=". The following example demonstrates the use of matching relational operatorswhich don’t require the use of a when-else statement as was the case prior to VHDL-2008.

Conditional Operator SupportVHDL 2008 adds a conditional operator "??" which converts bit/std_ulogic type to booleantype. This simplifies the task of writing conditional expressions. The operator is implicitlyinferenced in expressions by applying the operator tothe entire expression. The "??" operatorcan be used in ‘until’, ‘if’, ‘elseif’, ‘while’ and ‘when’ statements.

The following example shows implicit inference of the conditional operator.

Example

VHDL 2002 VHDL 2008

Parity <= data(0) xordata(1) xor data(2) xordata(3);

Parity <= xor data;

VHDL 2002 VHDL 2008

Control_sig <= '1' when x =y else '0'

Control_Sig <= x ?= y;

VHDL 2002 VHDL 2008

if a ='1' and b = '1' then Q <= d;end if;

if a and b then Q <= d;end if;

Page 76: PrecisionRTL Style

Precision Synthesis Style Guide, 2011a Update276

VHDL 2008 Language FeaturesMaximum and Minimum Function Support

November 2011

Maximum and Minimum Function SupportVHDL 2008 introduces pre-defined maximum and minimum functions with semantics"[ScalarType, ScalarType] return ScalarType" and "[DiscreteArrayType, DiscreteArrayType]return DiscreteArrayType".

Maximum and minimum functions make use of the "<" operator for ordering. VHDL 2008 alsopredefines maximum and minimum functions as reduction operators on array values withsemantic "[ArrayType] return ArrayElementType".

Unconstrained Record ElementsVHDL 2008 allows you to keep record elements unconstrained during type definition. Thesecan be constrained later during elaboration or signal declaration.

Example:

type myrec is recorda : std_logic_vector;b : bit;c : bit_vector;end record;

signal s : myrec((3 downto 0), open, (2 downto 0));

In this example, the constraints of ‘a’ and ‘c’ elements are defined only during signaldeclaration and not during type definition.

Page 77: PrecisionRTL Style

Precision Synthesis Style Guide, 2011a Update2 77November 2011

Chapter 3Verilog Language Features

Verilog HDL is a high level description language for system and circuit design. The languagesupports various levels of abstraction. Where a regular netlist format supports only structuraldescription, Verilog supports a wide range of description styles. This includes structuraldescriptions, data flow descriptions and behavioral descriptions.

Verilog allows a mixture of various levels of design entry. Precision RTL Synthesis accepts alllevels of abstraction from Register-transfer-level down, and minimizes the amount of logicneeded, resulting in a final netlist description in the technology of your choice.

Verilog is completely simulatable, but not completely synthesizable. Some Verilog constructshave no valid representation in a digital circuit. Other constructs do, in theory, have arepresentation in a digital circuits, but cannot be reproduced with guaranteed accuracy. Delaytime modeling in Verilog is an example of that.

State-of-the-art synthesis algorithms can optimize Register Transfer Level (RTL) circuitdescriptions and target a specific technology. The synthesis result of a Verilog design dependson the style of Verilog that is used. You should understand the concepts of synthesis-specificVerilog coding style at the RTL level, in order to achieve the desired circuit implementation.

This manual is intended to give the Verilog designer guidelines to achieve a circuitimplementation that satisfies the timing and area constraints that are set for the target circuit,while still using a high level of abstraction in the Verilog source code. This goal will bediscussed both in the general case for synthesis applications, as well as for Precision RTLSynthesis specifically. Examples are used extensively; Verilog rules are not emphasized.

Knowledge of the basic constructs of Verilog is assumed. For more information on the Veriloglanguage, refer to the Verilog Hardware Description Language Reference Manual, publishedby Open Verilog International.

This chapter provides an introduction to the basic language constructs in Verilog:

• Defining logic blocks:

• Data flow and behavioral descriptions

• Concurrent and sequential functionality

• Numbers and data types.

Precision synthesizes all levels of abstraction and minimizes the amount of logic neededresulting in a final netlist description in the technology of your choice.

Page 78: PrecisionRTL Style

Precision Synthesis Style Guide, 2011a Update278

Verilog Language FeaturesModules

November 2011

ModulesA basic building block in Verilog is a module. The module describes both the boundaries of thelogic block and the contents of the block, in structural, data flow and behavioral constructs.

NotePrecision RTL Synthesis supports empty top level modules.

This Verilog description shows the implementation of small_block, a block that describessome simple logic functions.

The port list is declared, the port directions are specified, then an internal wire is declared. Awire in Verilog represents physical connection in hardware. It can connect between modules orgates, and does not store a value. A wire can be used anywhere inside the module, but can onlybe assigned by:

• Connecting it to an output of a gate or a module.

• Assigning to it using a continuous assignment.

This module contains only dataflow behavior. Dataflow behavior is described using continuousassignments. All continuous assignments are executed concurrently, thus the order of theseassignments does not matter. This is why it is valid to use s before s is assigned. In the firststatement o1 is assigned the result of the logical OR of s and c. “| |” denotes the logical ORoperation.

More details about the various dataflow statements and operators are given in the followingsections.

’macromodule’Precision RTL Synthesis supports ’macromodule’, which is treated as ’module’.

module small_block (a, b, c, o1, o2);input a, b, c;output o1, o2;wire s;

assign o1 = s || c ;assign s = a && b ;assign o2 = s ^ c ;

endmodule

Page 79: PrecisionRTL Style

Verilog Language FeaturesNumbers

Precision Synthesis Style Guide, 2011a Update2 79November 2011

NumbersNumbers in Verilog can be either constants or parameters. Constants can be either sized orunsized. Either one can be specified in binary, octal, hexadecimal, or decimal format.

If a prefix is preceded by a number, this number defines the bit width of the number, forinstance, 8’b 01010101. If no such number exists, the number is assumed to be 32 bits wide. Ifno prefix is specified, the number is assumed to be 32 bits decimal.

Precision RTL Synthesis produces a warning when encountering non-synthesizable constantssuch as float. The value 0 is assumed.

For example, in

x will evaluate to 8.

Special characters in numbers:

Examples:

Name Prefix Legal Characters

binary ’b 01xXzZ_?

octal ’o 0-7xXzZ_?

decimal ’d 0-9_

hexcadecimal ’h 0-9a-fA-FxXzZ_?

x = 2.5 + 8;

“_” A separator to improve readability.

’x’, ’X’ Unknown value.

’z’, ’Z’, ’?’ Tri-state value.

334 32 bits wide decimal number

32’b101 32 bits wide binary number (zero leftfilled)

3’b11 3 bits wide binary number (i.e. 011)

20’h’f_ffff 20 bits wide hexadecimal number

10’bZ 10 bits wide all tri-state

Page 80: PrecisionRTL Style

Precision Synthesis Style Guide, 2011a Update280

Verilog Language FeaturesData Types

November 2011

Data TypesVerilog defines three main data types:

• net

• register

• parameter

By default these data types are scalars, but all can take an optional range specification as ameans of creating a bit vector. The range expression is of the following form:

Some of these data types are used in the example below, along with the range expression syntax.Further details on the data types are presented in the following sections.

[<most significant bit> : <least significant bit>]

// This design implements a Manchester Encoder//module manenc (clk , data , load , sdata, ready);parameter max_count = 7;

input clk, load;input [max_count:0] data;output sdata, ready ;

reg sdata, ready ;reg [2:0] count;reg [max_count:0] sout;reg phase;

// Phase encodingalways @ (posedge clk)

beginsdata = sout[max_count] ^ phase;phase = ~phase ;

end

Page 81: PrecisionRTL Style

Verilog Language FeaturesData Types

Precision Synthesis Style Guide, 2011a Update2 81November 2011

Net Data TypesThe net data types supported by Precision RTL Synthesis are

• wire

• tri

• supply0

• supply1

• wand

• wor

These data types are used to represent physical connections between structural entities in theVerilog design, such as a wire between two gates, or a tristate bus. Values cannot be assigned tonet data types within always blocks. (tri0, tri1, triand, trior and trireg are also net datatypes, but are not yet supported by Precision RTL Synthesis).

// Shift dataalways @ (posedge phase)

beginif ((count == 0) & !load) begin

sout[max_count:1] = sout[max_count - 1 :0];sout[0] = 1'b0;ready = 1'b1;

endelse if ((count == 0) & load ) begin

sout = data;count = count + 1;ready = 1'b0;

endelse if (count == max_count) begin

sout[max_count:1] = sout[max_count - 1 :0];sout[0]= 1'b0;count = 0;

endelse begin

sout[max_count:1] = sout[max_count - 1 :0];sout[0]= 1'b0;count = count + 1;

endend

endmodule

Page 82: PrecisionRTL Style

Precision Synthesis Style Guide, 2011a Update282

Verilog Language FeaturesData Types

November 2011

wire and tri NetsThe wire and tri net data types are identical in usage (syntax and function). The two differentnames are provided for design clarity. Nets driven by a single gate are usually declared as wirenets, as shown in Modules in this chapter, while nets driven by multiple gates are usuallydeclared as tri nets.

Supply NetsThe supply1 and supply0 net data types are used to describe the power (VCC) and groundsupplies in the circuit. For example, to declare a ground net with the name GND, the followingcode is used:

WAND and WOR Net TypesVerilog wand and wor statements result into AND and OR logic respectively, since wired logicis not available in all technologies.

Register Data TypeA register, declared with keyword reg, represents a variable in Verilog. Where net data types donot store values, reg data types do. Registers can be assigned only in an always block, task orfunction. When a variable is assigned a value in an always block that has a clock edge eventexpression (posedge or negedge), a flip-flop is synthesized by Precision RTL Synthesis. Toavoid the creation of flip-flops for reg data types, separate the combinational logic into adifferent always block (that does not have a clock edge event expression as a trigger).

Parameter Data TypeThe parameter data type is used to represent constants in Verilog. Parameters are declared byusing the keyword parameter and a default value. Parameters can be overridden when amodule is instantiated.

supply0 GND ;

wor out;out = a&bout = c&d;endmodule

Page 83: PrecisionRTL Style

Verilog Language FeaturesContinuous Assignments

Precision Synthesis Style Guide, 2011a Update2 83November 2011

Declaration Local to Begin-End BlockLocal declaration of registers and integers is allowed inside a named begin-end block. If thebegin-end block contains a “@ posedge ck” statement, then the declaration is not supported.

Array of Reg and Integer DeclarationMemory declaration and usage of an array of registers or integers is now allowed.

Continuous AssignmentsA continuous assignment is used to assign values to nets and ports. The nets or ports may beeither scalar or vector in nature. (Assignments to a bit select or a constant part select of a vectorare also allowed.) Because nets and ports are being assigned values, continuous assignments areallowed only in the dataflow portion of the module. As such, the net or port is updated wheneverthe value being assigned to it changes.

Continuous assignments may be made at the same time the net is declared, or by using theassign statement.

Net Declaration AssignmentThe net declaration assignment uses the same statement for both the declaration of the net andthe continuous assignment:

Only one net declaration assignment can be made to a specific net, in contrast to the continuousassignment statement, where multiple assignments are allowed.

input [10:0] data;always @ (data)begin: named_blockinteger i;

parity = 0;for (i = 0; i < 11; i= i + 1)parity = parity ^ data[i];

end //named_block

input [3:0] address;input [7:0] date_in;output [7:0] data_out;reg [7:0] data_out, mem [3:0];always @ (address or date_in or we)

if (we) mem [address] = date_in;else data_out = mem [address];

wire [1:0] sel = selector ;

Page 84: PrecisionRTL Style

Precision Synthesis Style Guide, 2011a Update284

Verilog Language FeaturesProcedural Assignments

November 2011

Continuous Assignment StatementThe continuous assignment statement (assign) is used to assign values to nets and ports thathave previously been declared.

The following example describes a circuit that loads a source vector of 4 bits on the edge of aclock (wrclk), and stores the value internally in a register (intreg) if the chip enable (ce) isactive. One bit of the register output is put on a tristate bus (result_int) based on a bit selectorsignal (selector), with the bus output clocked through a final register (result).

Procedural AssignmentsProcedural assignments are different from continuous assignments in that proceduralassignments are used to update register variables. Assignments may be made to the completevariable, or to a bit select or part select of the register variable.

Both blocking and non-blocking procedural assignments are allowed.

Blocking assignments, specified with the “=” operator, are used to designate assignments thatmust be executed before the execution of the statements that follow it in a sequential block. Thismeans that the value of a register variable in a blocking assignment is updated immediately afterthe assignment.

module tri_asgn (source, ce, wrclk, selector, result) ;input [3:0] source ;input ce, wrclk ;input [1:0] selector ;output result ;reg [3:0] intreg ;reg result ;// net declaration assignmentwire [1:0] sel = selector ;tri result_int ;

// continuous assignment statementassign

result_int = (sel == 2’b00) ? intreg[0] : 1’bZ ,result_int = (sel == 2’b01) ? intreg[1] : 1’bZ ,result_int = (sel == 2’b10) ? intreg[2] : 1’bZ ,result_int = (sel == 2’b11) ? intreg[3] : 1’bZ ;

always @(posedge wrclk)begin

if (ce)begin

intreg = source ;result = result_int ;

endend

endmodule

Page 85: PrecisionRTL Style

Verilog Language FeaturesAlways Blocks

Precision Synthesis Style Guide, 2011a Update2 85November 2011

Non-blocking assignments, specified with the “<=” operator, are used to schedule assignmentswithout blocking the procedural flow. It can be used whenever register assignments within thesame time step can be made without regard to order or dependence upon each other.

Also, in contrast to the blocking assignment, the value of a register variable in a non-blockingassignment is updated at the end of the time step. This behavior does not affect assignmentsdone in the dataflow environment, since assignments are done concurrently there. However, in asequential block, such as an always block, the value of the variable in a non-blockingassignment changes only after the complete execution of the sequential block.

Always BlocksAlways blocks are sections of sequentially executed statements, as opposed to the dataflowenvironment, where all statements are executed concurrently. In an always block, the order ofthe statements does matter. In fact, always blocks resemble the sequential coding style of highlevel programming languages. Also, always blocks offer a variety of powerful statements andconstructs that make them very suitable for high level behavioral descriptions.

An always block can be called from the dataflow area. Each always block is a sequentiallyexecuted program, but all always blocks run concurrently. In a sense, multiple always blocksresemble multiple programs that can run simultaneously. Always blocks communicate witheach other via variables of type reg which are declared in the module. Also, the ports and wires

defined in the module can be used in the always blocks.

module mux_case (source, ce, wrclk, selector, result);input [3:0] source;input ce, wrclk;input [1:0] selector;output result;reg [3:0] intreg;reg result, result_int;

always @(posedge wrclk)begin

if (ce)intreg = source;

result = result_int;end

always @(intreg or selector)case (selector)

2’b00: result_int = intreg[0];2’b01: result_int = intreg[1];2’b10: result_int = intreg[2];2’b11: result_int = intreg[3];

endcase

endmodule

Page 86: PrecisionRTL Style

Precision Synthesis Style Guide, 2011a Update286

Verilog Language FeaturesAlways Blocks

November 2011

This example describes a circuit that can load a source vector of 4 bits, on the edge of a writeclock (wrclk), store the value internally in a register (intreg) if a chip enable (ce) is active,while it produces one bit of the register constantly (not synchronized). The bit is selected by aselector signal of 2 bits, and is clocked out through the register result.

The description consists of two always blocks, one to write the value into the internal registerand clock the output, and one to read from it. The two always blocks communicate via theregister values intreg and result_int.

The first always block is a synchronous block. As is explained later, the always block executesonly if the event expression at the event control evaluates to true. In this case, the eventexpression evaluates to true when a positive edge occurs on the input wrclk (event expressionposedge wrclk). Each time the edge occurs, the statements inside the always statement areexecuted. In this case, the value of the input source is loaded into the internal variable intreg

only if ce is ’1’. If ce is ’0’, intreg retains its value. In synthesis terms, this translates into aD flip-flop, clocked on wrclk, and enabled by ce. Also, the intermediate output result_int isloaded into the output result (a D flip-flop clocked on wrclk).

The second always block is a combinational block. In this case, the event expression evaluatesto true when either intreg or selector changes. When this happens, the statements inside thealways statement are executed, and the output result_int gets updated depending on thevalues of intreg and selector. Note that this leads to combinational behavior (essentially amultiplexer), since result_int only depends on intreg and selector, and each time either ofthese signals changes, result_int gets updated.

The reason for separating the two always blocks is to avoid the creation of a register for thevariable result_int. result_int must be of reg data type, because it is assigned in an always

block, but it does not need to be registered logic.

Not all constructs, or combinations of constructs, in an always block lead to behavior that canbe implemented as logic. Precision RTL Synthesis supports empty always statements.

Note that constants on the sensitivity list have no effect in simulation or synthesis. Any kind ofexpression inside a sensitivity list is legal in Verilog and is accepted by the synthesis tools. Forsynthesis, all the leaf level identifiers of the expression are considered to be in the sensitivitylist, so some simulation mismatch might be seen after synthesis.

always @ (inp1[2:0] or 3'b011 or {a, b}) // allowed..................

Page 87: PrecisionRTL Style

Verilog Language FeaturesModule Instantiation

Precision Synthesis Style Guide, 2011a Update2 87November 2011

Module Instantiation

Technology-Specific MacrosIn many cases, the target technology library includes a number of hard macros and soft macrosthat perform specific arithmetic logic functions. These macros are optimized for the targettechnology and have high performance.

With Precision RTL Synthesis, it is possible to use component instantiation of soft macros orhard macros in the target technology. An added benefit is that the time needed for optimizationof the whole circuit can be significantly reduced since the synthesis tools do not have tooptimize the implementation of the dedicated functions any more.

Suppose you want to add two 8 bit vectors, and there is an 8 bit adder macro available in yourtarget technology. You could use the “+” operator to add these two vectors. The alternative is todefine a component that has the same name and inputs and outputs as the hard macro you wantto use. Instantiate the component in your Verilog description and connect the inputs and outputto the their appropriate signals. Precision RTL Synthesis instantiates the hard macro withouthaving to bother with the complicated optimization of the internal logic implemented by themacro.

This speeds up the optimization process considerably. In the netlist produced by Precision RTLSynthesis, the macro appears as a “black box” that the downstream place and route toolsrecognize.

If your arithmetic functions cannot be expressed in hard macros or soft macros immediately (forinstance if you need a 32 bit adder, but only have an 8 bit adder macro), you could write aVerilog description that instantiates the appropriate number of these macros.

Page 88: PrecisionRTL Style

Precision Synthesis Style Guide, 2011a Update288

Verilog Language FeaturesTechnology-Specific Macros

November 2011

Module instantiation can be used to implement individual gates or cells, macros, or to addhierarchy to your design. Here is an example that generates an address for RAM and instantiatesthe RAM cells:

For this example, if the RAM module RAM_32x1 is a cell or macro in a library, Precision RTLSynthesis will implement that cell or macro in the output netlist. To do that, the library in whichthe cell or macro exists must be specified as the Technology in the Setup Design step.

Precision RTL Synthesis supports empty named port connections, e.g.,

module scanner (reset, stop, load, clk, load_value, data) ;input reset, stop, load, clk;input [3:0] load_value;output [3:0] data;reg [4:0] addr;

// Instantiate and connect 4 32x1-bit ramsRAM_32x1 U0 (.a(addr), .d(load_value[0]), .we(load), .o(data[0]) );RAM_32x1 U1 (.a(addr), .d(load_value[1]), .we(load), .o(data[1]) );RAM_32x1 U2 (.a(addr), .d(load_value[2]), .we(load), .o(data[2]) );RAM_32x1 U3 (.a(addr), .d(load_value[3]), .we(load), .o(data[3]) );

// Generate the address for the ramsalways @(posedge clk or posedge reset)begin

if (reset)addr = 5’b0 ;

else if (~stop )addr = addr + 5’b1 ;

endendmodule

module RAM_32x1 ( a, we, d, o);input [4:0] a;input we, d ;output o;endmodule

nd2 x1 (.a(f), .b());

Page 89: PrecisionRTL Style

Verilog Language FeaturesTechnology-Specific Macros

Precision Synthesis Style Guide, 2011a Update2 89November 2011

Parameter Override During Instantiation of ModuleParameter overriding during module instantiation is supported by Precision RTL Synthesis.

Defparam StatementWhen using the defparam statement, parameter values can be changed in any module instancethroughout the design, provided the hierarchical name of the parameter is used.

NoteIn Precision RTL Synthesis, the hierarchical name is restricted to single level only. Thismeans that when the defparam statement is used, you can override any parameter value ofan instance in the current module only.

Example 3-1. Verilog Defparm

’unconnected_drive’ and ’nounconnected_drive’These directives are specified as outside modules only. ’unconnected_drive’ takes eitherpull0 or pull1 as a parameter and causes all the unconnected input ports to be pulled down or

module top (a, b);input [3:0] a;output [3:0] b;

do_assign #(4) name (a, b);endmodulemodule do_assign (a, b);

parameter n = 2;input [n-1:0] a;output [n-1:0] b;

assign b = a;endmodule

module top (a, b);input [3:0] a;output [3:0] b;wire top;do_assign name (a, b);defparam name.n = 4;endmodulemodule do_assign (a, b);parameter n = 2;input [n-1:0] a;output [n-1:0] b;assign b = a;endmodule

Page 90: PrecisionRTL Style

Precision Synthesis Style Guide, 2011a Update290

Verilog Language FeaturesOperators

November 2011

up, according to the parameter. ’nounconnected_ drive’ restores the normal condition(where the unconnected input ports are connected to high-Z).

OperatorsThis section describes the operators available for use in Verilog expressions.

OperandsAn operand in an expression can be one of the following:

• Number

• Net (including bit-select and part-select)

• Register (including bit-select and part-select)

• A call to a function that returns any of the above

Bit-selects take the value of a specific bit from a vector net or register. Part-selects are a set oftwo or more contiguous bits from a vector net or register. For example:

’unconnected_drive’ pull1module with_unconn_port (o, i);output o;input i;assign o = i;endmodule’nounconnected_drive’module test (i, o1, o2);input i;output o1, o2;with_unconn_port I1 (o1,); // o1 = 1with_unconn_port I2 (o2, i); // o2 = iendmodule

...wire bit_int ;reg [1:0] part_int ;reg [3:0] intreg;

bit_int = intreg[1] ;// bit-select of intreg assigned to bit_intpart_int = intreg[2:1] ;// part-select of intreg assigned topart_int...

Page 91: PrecisionRTL Style

Verilog Language FeaturesOperators

Precision Synthesis Style Guide, 2011a Update2 91November 2011

The operators supported by Precision RTL Synthesis are listed in Table 3-1.

Arithmetic OperatorsPrecision RTL Synthesis supports the following arithmetic operators:

If the bit value of any operand is ‘X’ (unknown), then the entire resulting value is ‘X’. The “/”operator is supported in the case where the divisor is a constant and a power of two.

Table 3-1. Operators Supported by Precision RTL Synthesis

Operator Description

+ - * / arithmetic

< > <= >= relational

== logical equality

!= logic inequality

! logical negation

&& logical and

|| logical or

~ bit-wise negation

& bit-wise and

| bit-wise inclusive or

^ bit-wise exclusive or

^~ or ~^ bit-wise equivalence

& reduction and

| reduction or

^ reduction xor

<< left shift

>> right shift

? : conditional

{} concatenation

+ - * /

Page 92: PrecisionRTL Style

Precision Synthesis Style Guide, 2011a Update292

Verilog Language FeaturesOperators

November 2011

Relational and Equality OperatorsPrecision RTL Synthesis supports the following relational and equality operators:

If the bit value of any operand is ‘X’ (unknown), then the entire resulting value is ‘X’.

=== and !== Operators are Treated as == and !=

=== and !== operators are treated as == and != for synthesis purposes if either one of theoperands is nonconstant. If both the operands are constant, they can be used to comparemetalogical values. In simulation, the difference between == and === is that one can comparemetalogical characters exactly with === but not with ==. Any metalogical character causes theoutput of == to be unknown x. The difference between != and !== is the same.

Logical OperatorsPrecision RTL Synthesis supports the following logical operators:

< > <= >= == !=

module triple_eq_neq (in1, in2, O);output [10:0] O;input [2:0] in1, in2;assign O[0] = 3'b0x0 === 3'b0x0, // output is 1 O[1] = 3'b0x0 !== 3'b0x0, // output is 0 O[2] = 3'b0x0 === 3'b1x0, // output is 0 O[3] = 3'b0x0 !== 3'b1x0, // output is 1O[4]=in1===3'b0x0,

// LHS is non constant so this// produces warning that comparison// metalogical character is// with zero. output is 0

O[5] = in1 !== 3'b0x0, // LHS is non constant so this// produces warning that comparison// with metalogical character is// zero.output is 1,because it// checks for not equality

O[6] = in1 === 3'b010, // normal comparison O[7] = in1 !== 3'b010, // normal comparison O[8] = in1 === in2, // normal comparison O[9] = in1 !== in2, // normal comparison O[10] = 3'b00x === 1'bx; // output is 1endmodule

! && ||

Page 93: PrecisionRTL Style

Verilog Language FeaturesOperators

Precision Synthesis Style Guide, 2011a Update2 93November 2011

Bit-Wise OperatorsPrecision RTL Synthesis supports the following bit_wise operators:

These operators perform bit-wise operations on equivalent bits in the operands.

Reduction OperatorsPrecision RTL Synthesis supports the following reduction operators:

These operators perform reduction operations on a single operand. Operations are performed onthe first and second bits of the operand, then on the result of that operation with the third bit ofthe operand, until the limit of the vector is reached. The result is a single bit value.

The following operators:

are negations of the “&”, “|”, and “^” operators.

Shift OperatorsPrecision RTL Synthesis supports the following shift operators:

Conditional OperatorThe conditional operator statement has the following syntax:

~ & | ^ ^~ ~^

& | ^

~& ~| ~^

<< >>

conditional_expression ? true_expression : false_expression

Page 94: PrecisionRTL Style

Precision Synthesis Style Guide, 2011a Update294

Verilog Language FeaturesOperators

November 2011

The result of this operation is true_expression if conditional_expression evaluates totrue, and false_expression if false. In the following example, result is assigned the value ofintreg[0] if sel = 2’b00, otherwise result is assigned Z:

ConcatenationThe concatenation of bits from multiple expressions is accomplished using the characters { and}. For example, the following expressions are equivalent:

For a = 5’b11010, c = 5’b10101, the result is foo = 5’b11001.

‘signed and ‘unsigned Attributes on Operators‘signed and ‘unsigned attributes change the type of a particular operator. Comparisonbetween two bit vectors are always done unsigned, but if the functionality needs to be signed, a‘signed attribute can be used just after the comparator.

Similarly, an ‘unsigned attribute can be used to perform an unsigned operation between twointegers.

The shift operators always do a logical shift. By using the ‘signed directive, they can be madeto do an arithmetic shift. Arithmetic right shift shifts in the sign bit and the left shift shifts in theleast significant bit (e.g., 4’b0001 << ‘signed 1 produces 4’b0011).

Operator PrecedenceThe operator precedence rules determine the order in which operations are performed in a givenexpression. Parentheses can be used to change the order in an expression. The operators

...output result ;reg [3:0} intreg ;wire [1:0] sel ;

assign result = (~sel[0] && ~sel[1]) ? intreg[0] : 1’bZ ;...

foo = {a[4:3], 1’b0, c[1:0]} ;foo = {a[4], a[3], 1’b0, c[1], c[0]} ;

input [3:0] A, B;output o;assign o = A < ‘signed B; // Signed comparator.

Page 95: PrecisionRTL Style

Verilog Language FeaturesStatements

Precision Synthesis Style Guide, 2011a Update2 95November 2011

supported by Precision RTL Synthesis are listed below in order from highest precedence tolowest, with operators on the same line having the same precedence.

StatementsThis section presents information on the use of if-else, case and for statements forspecifying designs.

If-Else StatementsThe if-else conditional construct is used to specify conditional decisions. As an example, hereis the design from “Procedural Assignments,” with the multiplexer described with this constructinstead of the case statement:

+ - ! ~ (unary)* / (binary)+ - (binary)<< >>< > <= >=== !=&^ ^~ ~^|&&||? : (ternary)

module mux_case (source, ce, wrclk, selector, result);input [3:0]source;input ce, wrclk;input [1:0]selector;output result;

reg [3:0]intreg;reg result, result_int;

always @(posedge wrclk)begin// if statement for chip enable on register

if (ce)intreg = source;

result = result_int;end

always @(intreg or selector)begin

Page 96: PrecisionRTL Style

Precision Synthesis Style Guide, 2011a Update296

Verilog Language FeaturesStatements

November 2011

This example describes a circuit that can load a source vector of 4 bits, on the edge of a writeclock (wrclk), store the value internally in a register (intreg) if a chip enable (ce) is active,while it produces one bit of the register constantly (not synchronized). The bit is selected by aselector signal of 2 bits, and is clocked out through the register result.

Case StatementsIf many conditional clauses have to be performed on the same selection signal, a case statementis a better solution than the if-else construct. The following example describes a traffic lightcontroller (state machine with binary encoding):

// if-else construct for multiplexer functionalityif (sel == 2’b00)

result_int = intreg[0] ;else if (sel == 2’b01)

result_int = intreg[1] ;else if (sel == 2’b10)

result_int = intreg[2] ;else if (sel == 2’b11)

result_int = intreg[3] ;end

endmodule

module traffic (clock, sensor1, sensor2,red1, yellow1, green1, red2, yellow2, green2);

input clock, sensor1, sensor2;output red1, yellow1, green1, red2, yellow2, green2;parameterst0 = 0, st1 = 1, st2 = 2, st3 = 3,

st4 = 4, st5 = 5, st6 = 6, st7 = 7;reg [2:0] state, nxstate ;reg red1, yellow1, green1, red2, yellow2, green2;

always @(posedge clock)state = nxstate;

always @(state or sensor1 or sensor2)begin

red1 = 1’b0; yellow1 = 1’b0; green1 = 1’b0;red2 = 1’b0; yellow2 = 1’b0; green2 = 1’b0;

case (state)st0: begin

green1 = 1’b1;red2 = 1’b1;if (sensor2 == sensor1)

nxstate = st1;else if (~sensor1 & sensor2)

nxstate = st2;end

Page 97: PrecisionRTL Style

Verilog Language FeaturesStatements

Precision Synthesis Style Guide, 2011a Update2 97November 2011

st1: begingreen1 = 1’b1;red2 = 1’b1;nxstate = st2;end

st2: begingreen1 = 1’b1;red2 = 1’b1;nxstate = st3;

end

st3: beginyellow1 = 1’b1;red2 = 1’b1;nxstate = st4;

end

st4: beginred1 = 1’b1;green2 = 1’b1;if (~sensor1 & ~sensor2)

nxstate = st5;else if (sensor1 & ~sensor2)

nxstate = st6;end

st5: beginred1 = 1’b1;green2 = 1’b1;nxstate = st6;

end

st6: beginred1 = 1’b1;green2 = 1’b1;nxstate = st7;

end

st7: beginred1 = 1’b1;yellow2 = 1’b1;nxstate = st0;

endendcase

endendmodule

Page 98: PrecisionRTL Style

Precision Synthesis Style Guide, 2011a Update298

Verilog Language FeaturesStatements

November 2011

Case Statement and Multiplexer GenerationThe case statement, as defined by the Verilog LRM, is evaluated by order, and the firstexpression to match the control expression is executed (during simulation). For synthesis, thisimplies a priority encoding. However, in many cases the case statement is used to imply amultiplexer. This is true whenever the case conditions are mutually exclusive (the controlexpressions equal only one condition at any given time).

In Verilog, the case items can be non-constants also. In such a situation, Precision RTLSynthesis cannot automatically detect that the case statements are full or parallel, so you caninclude a Verilog directive that tells the tool whether it is full or parallel. Refer the topicSynthesis Directives on page 109 for details.

Consider the following Verilog code fragment:

This code results in the equation:

If parallel_case is specified, the following equation will be synthesized:

This equation is simpler than the first. For a bigger case statement the amount of logicreduction can be significant. This cannot be determined automatically since the case items arenonconstants.

NoteUsing these directives can cause simulation differences between behavioral and post-synthesis netlists.

case (1’b1)s[0]: o = a;s[1]: o = b;

endcase

o = s[0] * a + !s[0] * s[1] * b;

o = s[0] * a + s[1] * b;

Page 99: PrecisionRTL Style

Verilog Language FeaturesStatements

Precision Synthesis Style Guide, 2011a Update2 99November 2011

Automatic Full Case DetectionThe casex statement below is full case (it covers all possible values 000 to 111). The defaultstatement is not necessary and is ignored by the synthesis tool, resulting in a warning message.The synthesis tools also do full-case detection for normal case and casez statements.

Precision RTL Synthesis does full coverage analysis for the if-then-else structure. Thefollowing example is considered a full if-then-else. The last else is ignored and a warning isissued.

Automatic Parallel Case Detectioncasex statements are priority-encoded by definition. Precision RTL Synthesis automaticallydetects parallel case and produce a warning message saying that case conditions are mutuallyexclusive. The following case statement is treated as parallel case.

input [2:0] sel;casex (sel)

3'b10x: ...3'bx10: ...3'bx11: ...3'b00x: ...default: ....

endcase

wire [1:0] data;if (data == 2) ...........else if (data == 1) ...........else if (data == 3) ...........else if (data == 0) ...........else // Ignored for synthesis purposeendmodule

input [2:0] sel;casex (sel)

3'b10x: ...3'bx10: ...3'bx11: ...3'b00x: ...default: ....

endcase

Page 100: PrecisionRTL Style

Precision Synthesis Style Guide, 2011a Update2100

Verilog Language FeaturesStatements

November 2011

Precision RTL Synthesis does parallel case detection for case and casez statements. It alsoextracts the parallelism of a mutually exclusive if-then-else structure as shown below.

casex StatementThe casex statement is used when comparison to only a subset of the selection signal is desired.For example, in the following Verilog code only the three least significant bits of vect arecompared to 001. The comparison ignores the three most significant bits.

casez Supportedcasez is used in Verilog to specify “don't care” bits of the case tags. The ’z’s in the case tagsare not compared when a comparison between the case expression sel and the tags is done.

’case’ and ’default’ StatementsPrecision RTL Synthesis allows the default statement to appear anywhere in a case, casez, orcasex statement, and supports the case statement with only one default entry.

wire [1:0] data;if (data == 2) ...........else if (data == 1) ...........else if (data == 3) ...........else if (data == 0) ...........

casex (vect)6’bXXX001 : <statement> ;

// this statement is executed if vect[2:0] = 3’b001endcase

...casez (sel)

3'b10z: ...3'bz10: ...3'bz11: ...3'b00z: ...default: ....

endcase

Page 101: PrecisionRTL Style

Verilog Language FeaturesStatements

Precision Synthesis Style Guide, 2011a Update2 101November 2011

NoteFor additional information on the handling of default statements during optimization,see “Advanced FSM Optimization” on page 296 and “How Precision Implements a SafeFSM” on page 297.

for Statementsfor loops are used for repetitive operations on vectors. In the following example, each bit of aninput signal is ANDed with a single bit enable signal to produce the result:

for loops are supported if they are bound by constants. for loops are also supported if theycontain a “@ posedge clk” statement which prevents infinite combinatorial loops.

...input clk ;reg [4:0] input_signal, result ;reg enable ;integer i;always @ (posedge clk)

for (i = 0; i < 5; i = i + 1)result[i] = enable & input_signal[i] ;

...

Page 102: PrecisionRTL Style

Precision Synthesis Style Guide, 2011a Update2102

Verilog Language FeaturesStatements

November 2011

Disable StatementThe disable statement disables a named block or a task. Disabling of one block from anotherblock is supported only if the second block is contained in the first one. Below is an example ofdisabling a named block.

module add_up_to (up_to_this, the_out);input [3:0] up_to_this;output the_out;reg [7:0] the_out;integer i;

always @ (up_to_this)begin: blk

the_out = 0;for (i = 0; i < 16; i = i + 1)begin

the_out = the_out + i;if (i == up_to_this) disable blk;

endendendmodule

//Below is an example of disabling a task.module add_up_to (up_to_this, the_out);input [3:0] up_to_this;output the_out;reg [7:0] the_out;

always @ (up_to_this)begin

add_upto_this (up_to_this, the_out);end

task add_upto_this;input [3:0] up_to_this;output [7:0] the_out;integer i;begin

the_out = 0;for (i = 0; i < 16; i = i + 1)begin

the_out = the_out + i;if (i == up_to_this) disable add_upto_this;

endendendtaskendmodule

Page 103: PrecisionRTL Style

Verilog Language FeaturesFunctions and Tasks

Precision Synthesis Style Guide, 2011a Update2 103November 2011

forever, repeat, while and Generalized Form of for Loopforever, repeat, while, and the generalized form of the for loop are supported as long as theysatisfy the conditions of for loops. The following forever example, is a counter withsynchronous reset.

If any loop construct is NOT bound by constants or by clock events, then Precision RTLSynthesis issues the “iteration limit reached” error.

Functions and TasksPieces of Verilog can be grouped together in functions and tasks, which can then be used assubprograms in the Verilog code. This is useful for repeated code, or for readability of the mainmodule.

Tasks and functions appear similar, but are used in different ways. A task is a subprogram withinputs and outputs, and replaces any piece of verilog code in a module. Expressions in a task canbe both combinational and sequential.

module forever_example (clk, reset, out);input clk, reset;output [3:0]out;reg [3:0]out;

alwaysbegin@(posedge clk) out = 0;begin: for_everforeverbegin: name@(posedge clk)if (reset) disable for_ever;out = out + 1;endendendendmodule

module repeat_example (i, o);input i;output o;reg o;

always @ (i)begin

o = i;repeat (4'b1011)

o = ~o; // o = ~iendendmodule

Page 104: PrecisionRTL Style

Precision Synthesis Style Guide, 2011a Update2104

Verilog Language FeaturesFunctions and Tasks

November 2011

Functions have only inputs and returns a value by its name. Functions are purely combinational.

FunctionsFunctions are defined inside a module and can be freely used once they are defined. Functionsare always used in an expression, behavioral or dataflow:

or

An example of a function is given below.

assign y = func(a,b);

x = func(z);

module calculator ( a, b, clk, s, operator );input [7:0] a, b;input clk;input [1:0] operator;output [7:0] s;reg [7:0] s;parameter ADD = 2’b00, SUB = 2’b01, MUL = 2’b10;

function [15:0] mult;input [ 7:0] a, b ;reg [15:0] r;integer i;

beginif (a[0] == 1)

r = b;else

r = 0;for (i = 1; i < 7; i = i + 1) begin

if (a[i] == 1 )r = r + b << i ;

endmult = r;

endendfunction

always @ (posedge clk)begin

case (operator)ADD: s = a + b ;SUB: s = a - b ;MUL: s = mult(a,b);

endcaseendendmodule

Page 105: PrecisionRTL Style

Verilog Language FeaturesFunctions and Tasks

Precision Synthesis Style Guide, 2011a Update2 105November 2011

TasksTasks are always displayed as statements:

Precision RTL Synthesis supports empty tasks.

An example of a task is presented below.

Inout Ports in TaskPrecision RTL Synthesis supports inout ports in a task statement. Any value passed throughinout ports can be used and modified inside the task.

my_task(a,b,c,d);

task demux ( state, load, bait, enable, ready, write, read );input [2:0] state;output load, bait, enable, ready, write, read;parameter LOAD = 3’b000, WAIT = 3’b100, ENAB = 3’b110,

READ = 3’b111, WRIT = 3’b011, STRO = 3’b001;

case (state)LOAD:

{state, load, bait, enable, ready, write, read} = 6’b100000;WAIT:

{state, load, bait, enable, ready, write, read} = 6’b010000;ENAB:

{state, load, bait, enable, ready, write, read} = 6’b001000;READ:

{state, load, bait, enable, ready, write, read} = 6’b000100;WRIT:

{state, load, bait, enable, ready, write, read} = 6’b000010;STRO:

{state, load, bait, enable, ready, write, read} = 6’b000001;endcase

endtask

module inoutintask (i, o1, o2);input i;output o1, o2;reg r, o1, o2;task T ;inout io;output o;

begino = io;io = ~io;

endendtask

Page 106: PrecisionRTL Style

Precision Synthesis Style Guide, 2011a Update2106

Verilog Language FeaturesSystem Task Calls

November 2011

Access of Global Variables from Functions and TasksGlobal variables can be accessed for both reading and writing.

System Task CallsPrecision RTL Synthesis accepts system task calls. System task calls are ignored and a warningis issued.

System Function CallsPrecision RTL Synthesis accepts system function calls. The value 0 is assumed for systemfunction calls and a warning is issued.

always @ (i)begin

r = i;T (r, o1); // o1 = i, r = ~io2 = r; // o2 = ~i;

endendmodule

module x (clk, reset, i1, i2, o);input clk, reset, i1, i2;output o;reg o;reg [1:0] state;

task T; //without any portbegin

case (state) 2'b00: o = i1; 2'b01: o = i2; 2'b10: o = ~i1; 2'b11: o = ~i2;

endcasestate = state + 1; // next state

endendtask

always @ (posedge clk or posedge reset)if (reset) begin state = 0; o = 0;endelse T;endmodule

Page 107: PrecisionRTL Style

Verilog Language FeaturesInitial Statement

Precision Synthesis Style Guide, 2011a Update2 107November 2011

Initial StatementPrecision RTL Synthesis accepts initial statements. The actual value is ignored.

Compiler DirectivesVerilog supports a large list of compiler directives. Most of them are useful for simulation, butare meaningless for synthesis purposes. A few directives are supported by the synthesis tools,and those directives have to do with macro substitution and conditional compilation. Followingis a list of these directives:

Verilog Issues and LimitationsVerilog is a language that has been developed for simulation purposes. Synthesis was not anissue in the development of the language. As a result, there are a number of Verilog constructsthat cannot be synthesized. There has been very little written that explains which constructscannot be synthesized into logic circuits and why.

This chapter provides explanations on why certain Verilog constructs cannot be synthesizedinto logic circuits and what changes have to be made to reach the intended behavior to obtain asynthesizable Verilog description.

Some obvious restrictions of the language are first presented, followed by a list summarizingVerilog syntax and semantic restrictions for Mentor Graphics synthesis tools. In addition, someguidelines are presented that should enable you to write Verilog that is easy to synthesize andgive you a feeling for synthesis complexity problems you might introduce when you write yourVerilog design.

Comparing With X and ZConsider the Verilog modeling case where an if clause should be entered if a part of a vector hasa particular value. The rest of the vector does not really matter. You might want to write this asfollows:

‘define‘ifdef‘else‘endif‘include‘signed‘unsigned‘unconnected_drive‘nounconnected_drive

if (vect == 6’bXXX001) begin ...

Page 108: PrecisionRTL Style

Precision Synthesis Style Guide, 2011a Update2108

Verilog Language FeaturesVerilog Issues and Limitations

November 2011

The user intention is to do a comparison to 001 (the right most three bits) and forget about theleft three bits. However, Verilog defines comparison on vectors as the AND of comparison ofeach individual element. Also, comparison of two elements is only true if both elements haveexactly the same value. This means that in order for this condition to be true, the three left mostbits have to be 'X'. But in logic synthesis, a bit can only be '0' or '1', so the condition isalways be false. In fact, this condition is not doing what was intended for simulation as well,since if any of the left most three bits does not have the value 'X' explicitly, the result is false.

However, comparison to 'X' is allowed using the casex construct. This is implemented in thefollowing manner:

In this case, only the three least significant bits of vect are compared to "001". The comparisonignores the three most significant bits.

Variable Indexing of Bit VectorsPrecision RTL Synthesis supports variable indexing of a vector. The limitation is that onlyvariable indexing of the form ’bit select’ is supported. Or more specifically, variable indexing ofthe form ’part select’ is not supported because it is not a synthesizable construct.

The semantics of variable indexing varies depending on whether the variable indexing is doneon the left hand side of an assignment or on the right hand side of the assignment. The right-hand side variable indexing generates a multiplexer controlled by the index. The left-handvariable indexing generates a de-multiplexer controlled by the index. set of decoders enabling.The following example shows both examples.

casex (vect)6’bXXX001 : <statement> ;

endcase

module tryit (input_bus, in_bit, control_input, output_bus, out_bit);input [3:0] input_bus ;input [1:0] control_input ;input in_bit ;output [3:0] output_bus ;output out_bit ;

reg [1:0] control_input ;reg [3:0] input_bus, output_bus ;reg in_bit, out_bit ;

always @ (control_input or input_bus or in_bit)begin

out_bit = input_bus [control_input] ;output_bus [control_input] = in_bit ;

endendmodule

Page 109: PrecisionRTL Style

Verilog Language FeaturesSynthesis Directives

Precision Synthesis Style Guide, 2011a Update2 109November 2011

Synthesis DirectivesVerilog pragmas are also called synthesis directives.

parallel_case and full_case directivesparallel_case and full_case directives are allowed as synthesis directive on a case by casebasis. Precision RTL Synthesis detects the true full and parallel cases automatically. However,there are cases (like onehot encoded state machine) that are not inherently parallel/full, but theenvironment guarantees that the case statement is parallel and/or full. In such a condition thefollowing two synthesis directives are very useful.

translate_off and translate_on directivestranslate_off and translate_on synthesis directives are allowed to comment out a portionof code that you may want to retain for some purpose other than synthesis.

State and S0, S1, S2, S3 are of enum type ee1. They cannot be used for any boolean or arithmeticoperation. Bit or port select from state or its values is also considered an error. Enumeratedtype module ports are not allowed.

attribute directiveYou can set attributes on design objects to refine and control the synthesis process. Forexample, by setting one of the pre-defined Precision inff, outff and triff attributes on asignal to true, you can improve the timing performance of the I/O by moving the first/lastregister in the path to the pad.

input [3:0] inp_state;// example of onehot encoded machinecase (1'b1) // pragma parallel_case full_case inp_state[0]: ....... inp_state[1]: ....... inp_state[2]: ....... inp_state[3]: .......endcase

// code for synthesis// pragma translate_off$display (.....); // not for synthesis// pragma translate_on// code for synthesisendmodule

Page 110: PrecisionRTL Style

Precision Synthesis Style Guide, 2011a Update2110

Verilog Language FeaturesSynthesis Directives

November 2011

NoteAn attribute can only be set on an object after the object is declared. The syntax of thisdirective is as follows:

// pragma attribute <object_name> <attribute_name> <attribute_value>

Verilog 2001 syntax is also supported:

(* synthesis, <attribute_name> [ = <optional_value> ] *)

As a synthesis directive inside a declaration:

wire [1:0] /* synthesis preserve_signal = 1 */ my_wire ;

Syntax and Semantic RestrictionsThe following list provides a summary of the syntax and semantic restrictions of the PrecisionRTL Synthesis Verilog HDL parser.

• UDP primitives

• specify block

• real variables and constants

• initial statement

• tri0, tri1, tri1, tri1, tri1, net types

• time data type

• Named events and event triggers

• The following gates: pulldown, pullup, nmos, mmos, pmos, rpmos, cmos,rcmos, tran, rtran, tranif0, rtranif0, tranif1, rtranif1

• wait statements

• Parallel block, join and for.

//examplemodule expr (a, b, c, out1, out2);input [15:0] a, b, c;output [15:0] out1, out2;

assign out1 = a + b;assign out2 = b + c;

// pragma attribute out1 modgen_sel fastestendmodule

Page 111: PrecisionRTL Style

Verilog Language FeaturesVerilog 2001 Support

Precision Synthesis Style Guide, 2011a Update2 111November 2011

• System task enable and system function call

• force statement

• release statement

• Blocking assignment with event control

• Named port specification (not to be confused with passing arguments by name, whichis supported)

• Concatenation in port specification

• Bit selection in port specification

• Procedural assign and de-assign

• Supported Verilog Features

• Edge triggers on sensitivity list must be single bit variable, or array indexing expression.

• Indexing of parameters is not allowed.

• Loops must be bounded by constants or contain (@ posedge clk) statement.

• Supported Verilog Features

• Delay and delay control.

• ’vectored’ declaration

Verilog 2001 SupportThe Verilog-2001 Standard was approved by the IEEE in June of 2000 and includesenhancements to the previously existing Verilog standard in the following areas:

• Enhance the Verilog language to help with today's deep-submicron and intellectualproperty modeling issues

• Ensure that all enhancements were both useful and practical, and that simulator andsynthesis vendors would implement Verilog-2001 in their products

• Correct any ambiguities in the Verilog-1995 standard (IEEE 1364-1995)

Verilog 2001 expands the construct set of Verilog - 1995 but does not replace or change thebehavior of previously implemented constructs. You may seamlessly mix new and previouslyexisting constructs.

Supported Verilog 2001 ConstructsPrecision Synthesis offers support for the following Verilog-2001 constructs:

Page 112: PrecisionRTL Style

Precision Synthesis Style Guide, 2011a Update2112

Verilog Language FeaturesVerilog 2001 Support

November 2011

• Signed arithmetic extensions

• Comma-separated sensitivity list

• Combinational logic sensitivity token

• Combined port / data type declarations

• ANSI-style port lists

• Power Operator

• Automatic width extension past 32 bits

• Register declaration with initialization

Detailed Description

Combinational logic sensitivity tokenTo properly model combinational logic using a Verilog always procedure, the sensitivity listmust include all input signals used by that block of logic. In large, complex blocks ofcombinational logic, it is easy to inadvertently omit an input from the sensitivity list, which canlead to simulation and synthesis mismatches.

Verilog-2000 adds a new wild card token, @*, which represents a combinational logicsensitivity list. The @* token indicates that the simulator or synthesis tool should automaticallybe sensitive to any values used by the procedure in decisions or in expressions on the right-handside of assignment statements. In the following example, the @* token will cause the procedureto automatically be sensitive to changes on sel, a or b.

always @* //combinational logic sensitivityif (sel)

y = a;else

y = b;

Combined port / data type operatorVerilog requires that signals connected to the input or outputs of a module have twodeclarations: the direction of the port, and the data type of the signal. In Verilog-1995, these twodeclarations had to be done as two separate statements. Verilog-2000 adds a simpler syntax, bycombining the declarations into one statement.

module mux8 (y, a, b, en);output reg [7:0] y;input wire [7:0] a, b;input wire en;

Page 113: PrecisionRTL Style

Verilog Language FeaturesVerilog 2001 Support

Precision Synthesis Style Guide, 2011a Update2 113November 2011

Power OperatorVerilog-2001 adds a power operator, represented by an ** token. This operator preforms similarfunctionality as the C pow() function. It will return a real number if either operand is a realvalue, and an integer value if both operands are integer values. One practical application of thepower operator is to calculate values such as 2n. For example:

always @(posedge clock)result = base ** exponent;

Signed Arithmetic ExtensionsFor integer math operations, Verilog uses the data types of the operands to determine if signedor unsigned arithmetic should be performed. If either operand is unsigned, unsigned operationsare performed. To perform signed arithmetic, both operands must be signed. In Verilog-1995,the integer data type is signed, and the reg and net data types are unsigned. A limitation inVerilog- 1995 is that the integer data type has a fixed vector size, which is 32-bits in mostVerilog simulators. Thus, signed integer math in Verilog-1995 is limited to 32-bit vectors. TheVerilog-2000 standard adds five enhancements to provide greater signed arithmetic capability:

• Reg and net data types can be declared as signed

• Function return values can be declared as signed

• Integer numbers in any radix can be declared as signed

• Operands can be converted from unsigned to signed

• Arithmetic shift operators have been added

The Verilog-1995 standard has a reserved keyword, signed, but this keyword was not used inVerilog-1995. Verilog-2000 uses this keyword to allow reg data types, net data types, ports, andfunctions to be declared as signed types. Some example declarations are:

reg signed [63:0] data;wire signed [7:0] vector;input signed [31:0] a;function signed [128:0] alu;

In Verilog-1995, a literal integer number with no radix specified is considered a signed value,but a literal integer with a radix specified is considered an unsigned value. Verilog-2000 adds anadditional specifier, the letter 's', which can be combined with the radix specifier, to indicate thatthe literal number is a signed value.

16'hC501 //an unsigned 16-bit hex value16'shC501 //a signed 16-bit hex value

In addition to being able to declare signed data types and values, Verilog-2000 adds two newsystem functions, $signed and $unsigned. These system functions are used to convert anunsigned value to signed, or vice-versa.

Page 114: PrecisionRTL Style

Precision Synthesis Style Guide, 2011a Update2114

Verilog Language FeaturesVerilog 2001 Support

November 2011

reg [63:0] a; //unsigned data typealways @(a) begin

result1 = a / 2; //unsigned arithmeticresult2 = $signed(a) / 2; //signed arithmetic

end

One more signed arithmetic enhancement in Verilog-2000 is arithmetic shift operators,represented by >>> and <<< tokens. An arithmetic right-shift operation maintains the sign of avalue, by filling with the sign-bit value as it shifts. For example, if the 8-bit variable Dcontained 8'b10100011, a logical right shift and an arithmetic right shift by 3 bits would yieldthe following:

D >> 3 //logical shift yields 8'b00010100D >>> 3 //arithmetic shift yields 8'b11110100

Comma-Separated Sensitivity ListVerilog-2000 adds a second way to list signals in a sensitivity list, by separating the signalnames with commas instead of the or keyword. The following two sensitivity lists arefunctionally identical:

always @(a or b or c or d or sel)always @(a, b, c, d, sel)

The new, comma-separated sensitivity list does not add any new functionality. It does, however,make Verilog syntax more intuitive, and more consistent with other signal lists in Verilog.

ANSI-Style Port ListsVerilog-1995 uses the older Kernighan and Ritchie C language syntax to declare module ports,where the order of the ports is defined within parentheses, and the declarations of the ports arelisted after the parentheses. Verilog-1995 tasks and functions omit the parentheses list, and usethe order of the input and output declarations to define the input/output order. Verilog-2000updates the syntax for declaring inputs and outputs of modules, tasks, and functions to be morelike the ANSI C language. That is, the declarations can be contained in the parentheses thatshow the order of inputs and outputs.

module mux8 ( output reg [7:0] y,input wire [7:0] a,input wire [7:0] b,input wire en );function [63:0] alu (

input [63:0] a,input [63:0] b,input [7:0] opcode );

Automatic Width Extension Past 32 BitsWith Verilog-1995, assigning an unsized high-impedance value (e.g.: 'bz) to a bus that is greaterthan 32 bits would only set the lower 32 bits to high-impedance. The upper bits would be set to

Page 115: PrecisionRTL Style

Verilog Language FeaturesVerilog 2001 Support

Precision Synthesis Style Guide, 2011a Update2 115November 2011

0. To set the entire bus to high-impedance requires explicitly specifying the number of highimpedance bits. For example:

Verilog-1995:parameter WIDTH = 64;reg [WIDTH-1:0] data;data = 'bz; //fills with 'h00000000zzzzzzzzdata = 64'bz; //fills with 'hzzzzzzzzzzzzzzzz

The fill rules in Verilog-1995 make it difficult to write models that are easily scaled to newvector sizes. redefinable parameters can be used to scale vector widths, but the Verilog sourcecode must still be modified to alter the literal value widths used in assignment statements.

Verilog-2000 changes the rule for assignment expansion so that an unsized value of Z or X willautomatically expand to fill the full width of the vector on the left-hand side of the assignment.

Verilog-2000:parameter WIDTH = 64;reg [WIDTH-1:0] data;data = 'bz; //fills with 'hzzzzzzzzzzzzzzzz

This Verilog-2001 enhancement is not backward compatible with Verilog-1995. However, theIEEE standards group felt the Verilog-1995 behavior was a bug in the standard that needed to becorrected. It is expected that all existing models with greater than 32-bit busses have avoidedthis bug by explicitly specifying the vector sizes. Therefore, there should not be anycompatibility problems with existing models.

Register Declaration with InitializationVerilog-2000 adds the ability to initialize variables at the time they are declared, instead ofrequiring a separate initial procedure to initialize variables. The initial value assigned to thevariable will take place within simulation time zero, just as if the value had been assignedwithin an initial procedure.

Verilog-1995:reg clock;initialclk = 0;Verilog-2000:reg clock = 0;

In-Line Parameter PassingVerilog-1995 has two methods of redefining parameters within a module instance: explicitredefinition using defparam statements, and in-line implicit redefinition using the # token aspart of the module instance. The latter method is more concise, but because it redefinesparameter by their declaration position, it is error-prone and is not self-documenting. Thefollowing example illustrates the two Verilog-1995 methods for parameter redefinition.

module ram (...);

Page 116: PrecisionRTL Style

Precision Synthesis Style Guide, 2011a Update2116

Verilog Language FeaturesVerilog 2001 Support

November 2011

parameter WIDTH = 8;parameter SIZE = 256;...endmodulemodule my_chip (...);...//Explicit parameter redefinition by nameRAM ram1 (...);defparam ram1.SIZE = 1023;//Implicit parameter redefintion by positionRAM #(8,1023) ram2 (...);endmodule

Verilog-2001 adds a third method to redefine parameters, in-line explicit redefinition. This newmethod allows inline parameter values to be listed in any order, and document the parametersbeing redefined.

//In-line explicit parameter redefintionRAM #(.SIZE(1023)) ram2 (...);

File and Line Compiler DirectivesVerilog tools need to keep track of the line number and the file name of Verilog source code.This information can be used for error messages, and can be accessed by the Verilog PLI. IfVerilog source is pre-processed by some other tool, however, the line and file information of theoriginal source code can be lost. Verilog-2001 adds a `line compiler directive, which can beused to specify the original source code line number and file name. This allows the location inan original file to be maintained if another process modifies the source, such as by adding orremoving lines of source text.

AttributesThe Verilog language was originally created as a hardware description language for digitalsimulation. As tools other than simulation have adopted Verilog as a source input, there hasbeen a need for these tools to be able add tool specific information to the Verilog language. InVerilog- 1995, there was no mechanism for adding tool-specific information, which led to non-standard methods, such as hiding synthesis commands in Verilog comments. Verilog-2001 addsa mechanism for specifying properties about objects, statements and groups of statements in theHDL source. These properties are referred to as attributes. Attributes are used by PrecisionSynthesis to apply optimization directives and thus control the results. An attribute is containedwithin the tokens (* and *). Attributes can be associated with all instances of an object, or witha specific instance of an object. Attributes can be assigned values, including strings, andattribute values can be re-defined for each instance of an object. Verilog-2001 does not defineany standard attributes. A complete list of supported attributes is provided in the Precision RTLSynthesis Reference Manual. An example is provided below:

(* parallel case *) case (1'b1) //1-hot FSMstate[0]: ...state[1]: ...state[2]: ...

Page 117: PrecisionRTL Style

Verilog Language FeaturesVerilog 2001 Support

Precision Synthesis Style Guide, 2011a Update2 117November 2011

endcase

Enhanced Conditional CompilationVerilog-1995 supports limited conditional compilation: `ifdef, `else, `endif, and `undef.Verilog-2001 adds two new directives: `ifndef and `elsif.

Page 118: PrecisionRTL Style

Precision Synthesis Style Guide, 2011a Update2118

Verilog Language FeaturesVerilog 2001 Support

November 2011

Page 119: PrecisionRTL Style

Precision Synthesis Style Guide, 2011a Update2 119November 2011

Chapter 4SystemVerilog Language Features

This section describes SystemVerilog constructs supported in Precision as well as anintroduction to the key features in the new language extension.

SystemVerilog Support in PrecisionThe synthesizable subset of SystemVerilog is supported in all versions of Precision (RTL, RTLPlus, and Physical) and strictly follows the syntax described in the IEEE Std 1800-2005specification. Supported constructs are shown in Table 4-1. Refer to the IEEE Std 1800-2005for details on each construct as well as the information presented in this section.

Table 4-1. Supported SystemVerilog Constructs

IEEE 1800-2005 SystemVerilog Construct

Literal Values

3.3 Integer and logic literals

3.6 String literals

3.7 Array literals

3.8 Structure literals

Data Types

4.3 Integer data types

4.5 Void data type

4.9 User-defined types

4.10 Enumerations

4.11 Structures and unions (packed unions only)

4.13 Singular and aggregate types

4.14 Casting

4.16 Bit-stream casting

4.17 Default attribute type

Arrays

5.2 Packed and unpacked arrays

5.3 Multiple dimensions

Page 120: PrecisionRTL Style

Precision Synthesis Style Guide, 2011a Update2120

SystemVerilog Language FeaturesSystemVerilog Support in Precision

November 2011

5.4 Indexing and slicing of arrays

5.5 Array querying functions

5.7 Array assignment

5.8 Arrays as arguments

Data Declarations

6.3 Constants

6.4 Variables

6.5 Nets

6.6 Scope and lifetime

6.7 Nets, regs, and logic

6.8 Signal aliasing

6.9 Type compatibility

Operators and Expressions

8.3 Assignment operators

8.4 Operations on logic and bit types

8.5 Wild equality and wild inequality

8.7 Size

8.8 Sign

8.9 Operator precedence and associativity

8.10 Buit-in Methods

8.11 Static Prefixes

8.12 Concatenation

8.13 Assignment patterns

8.15 Aggregate expressions

Procedural Statements

10.3 Blocking and nonblocking assignments

10.4 Selection statements

10.5 Loop statements (except foreach)

10.6 Jump statements

10.8 Named blocks and statement labels

10.10 Event control

Table 4-1. Supported SystemVerilog Constructs (cont.)

Page 121: PrecisionRTL Style

SystemVerilog Language FeaturesSystemVerilog Support in Precision

Precision Synthesis Style Guide, 2011a Update2 121November 2011

Processes

11.2 Combinational logic

11.3 Latched logic

11.4 Sequential logic

11.5 Continuous assignments

Tasks and Functions

12.2 Tasks

12.3 Functions

12.4 Task and function argument passing

12.5 Import and export function

Hierarchy

19.2 Packages

19.3 Compilation unit support

19.5 Module declarations

19.8 Port declarations (all types)

19.11 Module instances

19.12 Port connection rules

Interfaces

20.3 Ports in interfaces

20.4 Modports

20.6 Tasks and functions in interfaces

20.7 Parameterized interfaces

20.9 Acces to interface objects

System Tasks and System Functions

22.4 Expression size system function

22.7 Array querying system functions

Compiler Directives

23.2 `define macros

23.3 `include

Table 4-1. Supported SystemVerilog Constructs (cont.)

Page 122: PrecisionRTL Style

Precision Synthesis Style Guide, 2011a Update2122

SystemVerilog Language FeaturesHow Precision Reads SystemVerilog files

November 2011

How Precision Reads SystemVerilog filesPrecision’s default setting assumes that any file with a *.sv extension is a SystemVerilog filewhile any file with a *.v is a Verilog 2001 file.

Users commonly use the *.v extension when writing Verilog and SystemVerilog files. In thatcase, Precision’s file settings must be changed to assume that all *.v files will obeySystemVerilog syntax. Because SystemVerilog is largely backward compatible with Verilog,purely Verilog files will be read correctly. This can be done with the following command,

setup_design -language_syntax_verilog=sv

or via the GUI as shown in Figure 4-1, SystemVerilog File Settings.

Figure 4-1. SystemVerilog File Settings

Page 123: PrecisionRTL Style

SystemVerilog Language FeaturesCompilation Unit Scope Settings

Precision Synthesis Style Guide, 2011a Update2 123November 2011

Compilation Unit Scope SettingsA compilation-unit scope, as described in the IEEE 1800-2005 specification (section 19.3), is ascope that is local to the compilation unit. It contains all declarations that lie outside of anyother scope. SystemVerilog supports separate compilation using compiled units. Precisioncompiles each SystemVerilog into its own compilation unit. The declarations in eachcompilation unit scope are accessible only within its corresponding source file.

The compilation-unit scope allows users to easily share declarations (e.g., types) across the unitof compilation, but without having to declare a package from which the declarations aresubsequently imported. Thus, the compilation-unit scope is similar to an implicitly definedanonymous package. Because it has no name, the compilation-unit scope cannot be used with animport statement.

Altering the Compilation Unit ScopeThe Precision Synthesis tool provides two use models for defining which files constitute acompilation unit. The `include statement can be used to include the contents of a header file intothe compilation unit scope.

1. Each file is a separate compilation unit in which case the declarations in eachcompilation-unit scope are accessible only within its corresponding file (default flow).

2. All files on a given compilation command line make a single compilation unit in whichcase the declarations within those files are accessible anywhere else within theconstructs defined within those files. To enable this setting, enter the followingcommand in Precision:

setup_design -all_file_cunit_scope=true

NoteUsing a single compilation unit scope will cause Precision Synthesis to check for morethan one inclusion (`include) of a header file and issue an error message when thiscondition is detected. An example of this is shown in “One Compile Unit Scope ErrorExample 1” on page 124.

In “Compilation Unit Scope Example 1” on page 123 and “Compilation Unit Scope Example 2”on page 124, the typedef declaration “T” can be made visible in module "middle" (file namedmiddle.sv) using the -all_file_cunit_scope=true option.

Compilation Unit Scope Example 1In this example, module named "top" has a type definition "T" that is visible because it isdeclared in the compilation unit scope of file top.sv. Module named "middle" is defined in filemiddle.sv. The type definition "T" will not be visible to module "middle" because "T" isdeclared in different compilation unit scope.

Page 124: PrecisionRTL Style

Precision Synthesis Style Guide, 2011a Update2124

SystemVerilog Language FeaturesCompilation Unit Scope Settings

November 2011

File: top.svtypedef int T;module top;T in1; // T visible hereT out;assign out = in1;endmodule

File: middle.svmodule middle;T in1; // cannot refer to T as declared in compilation // unit scope of file top.svT out;endmodule

Compilation Unit Scope Example 2In this example, module named "middle" is defined in file middle.sv, cannot refer to typedefinition "T" because the typedef int T statement is in the compilation unit scope of file top.sv.

File: typedef.htypedef logic T;

File: top.sv`include typedef.hmodule top;T in1;T out;endmodule

File: middle.svmodule middle;T in1; //cannot refer to T as declared in Compilation //unit scope of file top.svT out;endmodule

This behavior is the default in Precision.

Normal Errors Related to Compilation Unit ScopeWhen option -all_file_cunit_scope is true.

One Compile Unit Scope Error Example 1Multiple declarations or multiple `include of the same header file leads to an error. Here is anexample of such multiple references.

File: top.sv`include typedef.hmodule top;endmodule

Page 125: PrecisionRTL Style

SystemVerilog Language FeaturesCompilation Unit Scope Settings

Precision Synthesis Style Guide, 2011a Update2 125November 2011

File: middle.sv`include typedef.hmodule middle;endmodule

Correction: This can be corrected by either defining `include typedef.h once, in case of singlecompilation unit scope, or using a guarded macro.

One Compile Unit Scope Error Example 2In this example, the file "top.sv" is compiled first; in module named "top" TYPDEF_H isdefined and then the typdef declaration "T" becomes visible. Secondly, file middle.sv iscompiled and because TYPEDEF_H is already defined, the type definition "T" does not occurin the scope of middle.sv.

File: typedef.h`ifndef TYPEDEF_H`define TYPEDEF_Htypedef int T`endif

File: top.svmodule top;`include typedef.hT in1;endmodule

File: middle.sv`include typedef.hmodule middle;T in1; //not visible hereendmodule

Correction: This can be corrected by moving the `include to only compilation unit scope asgiven below

File: top.sv`include typedef.hmodule top;endmodule

File: middle.sv`include typedef.hT in1; // visible here as T is declared in single // compilation unit scopemodule middle;endmodule

Page 126: PrecisionRTL Style

Precision Synthesis Style Guide, 2011a Update2126

SystemVerilog Language FeaturesCompilation Unit Scope Settings

November 2011

When Option -all_file_cunit_scope=false (Default inPrecision)

Default Compile Unit Scope Error Example 1In this case each file will have a separate compilation unit scope, therefore modules "top" and"middle" will have in1 variable with different enum typedef declaration.

SystemVerilog allows only the same enum type can be assigned to each other, so instantiationof "middle" in "top" results in connecting different enum declarations, resulting in an errormessage. Similar issues can arise in the case of unpacked structures and unions.

File: typedef.h`ifndef TYPEDEF_H`define TYPEDEF_Htypedef enum logic [1:0] {RED, GREEN, BLUE, BLACK} T;`endif

File: top.sv`include typedef.hmodule top;T in1;middle m1(.in1(in1)); // incorrect connection of in1 as enum variables // of different typedef.endmodule

File: middle.sv`include typedef.hmodule middle(in1);T input in1;endmodule

Correction: Set the option -all_file_cunit_scope=true which will create single typedefdeclaration in compilation unit scope for "T" and result in the enum variables being the sametype.

New Design Rules for Packages and Compilation Unit ScopePackages are not permitted to refer to compilation unit items. An example of such of referenceis the following small design

typedef int T;package p;T foo;endpackage

Packages may depend on other packages, so compilation unit declarations that packages needshould be factored into separate packages. For example, the previous design should be changedas shown:

package shared_types;

Page 127: PrecisionRTL Style

SystemVerilog Language FeaturesBasic Language Constructs

Precision Synthesis Style Guide, 2011a Update2 127November 2011

typedef int T; endpackage

package p; import shared_types::*; T foo; endpackage

It is important to note that "import" statements immediately before a package declaration arecompilation unit imports and not imports into the subsequent package. Package references maynot look into such an import. For example, the following approach will not work:

package shared_types; typedef int T; endpackage;

import shared_types::*; package p; T foo; // cannot refer to T since it is imported into // the compilation unit, not into the package endpackage

Designs must be factored so that packages do not refer to anything in the compilation unit.

Basic Language ConstructsThis section provides an introduction to basic language constructs in SystemVerilog. For this,you are required to know the basics of Verilog constructs. For more information on the Veriloglanguage, refer to the Verilog Hardware Description Language Reference Manual, published byOpen Verilog International.

The following basic language constructs in SystemVerilog are described in detail:

• Literal Values

• Data Types

• Arrays

• Data Declarations

• Attributes

• Operators and Expressions

• Procedural Statements and Control flow

• Processes

• Tasks and Functions

Page 128: PrecisionRTL Style

Precision Synthesis Style Guide, 2011a Update2128

SystemVerilog Language FeaturesBasic Language Constructs

November 2011

• Hierarchy

• Interfaces

• Compiler Directives

• Unpacked Array Concatenation

• Foreach Loop Support

• Removing Text Substitution Macros

• Set Membership Operator (Inside Operator)

Precision synthesizes all levels of abstraction and minimizes the amount of logic neededresulting in a final netlist description in the technology of your choice.

Literal ValuesLiteral value types that are supported in System Verilog include:

• Integer

• Logic

• Real

• String of type packed array

• Array

• Structure Literals

NoteThe SystemVerilog Time literal is not supported in Precision Synthesis.

Numbers in Verilog can be either constants or parameters. Constants can be either sized orunsized. Either one can be specified in binary, octal, hexadecimal, or decimal format.

If a prefix is preceded by a number, this number defines the bit width of the number, forinstance, 8’b 01010101. If no such number exists, the number is assumed to be 32 bits wide. Ifno prefix is specified, the number is assumed to be 32 bits decimal.

Name Prefix Legal Characters

binary ’b 01xXzZ_?

octal ’o 0-7xXzZ_?

decimal ’d 0-9_

hexcadecimal ’h 0-9a-fA-FxXzZ_?

Page 129: PrecisionRTL Style

SystemVerilog Language FeaturesBasic Language Constructs

Precision Synthesis Style Guide, 2011a Update2 129November 2011

Special characters in numbers:

Examples

Integer and Logic Literals (sized and unsized)

Examplemodule literal1(output int i1);

assign i1 = 32’d4; //32’b00000000000000000000000000000100logic [1:0][1:0] s1 = 4’bzzzz;logic [1:0][3:0] s2 = 8’d1; // 8’b00000001logic [1:0][7:0] l1 = ’0; // sets all bits to 0logic [1:0][7:0] l2 = ’1; // sets all bits to 1logic [1:0][7:0] l3 = ’x; // sets all bits to xlogic [1:0][7:0] l4 = ’z; // sets all bits to z......endmodule

Real Literals

Examplemodule literal2 #(parameter PI = 3.14) (input bit [2:0] sel , outputinteger out1);

parameter R = 134.09e-2;integer r1 = 2.1-2.3/1.2+1.7*3;integer r2 = 2.1e-30+3.1E31-7.902e33;integer r3 = (5.1e+31/2.3E34)*4.56+7.03E1;integer r4 = 2*PI*R;integer r5 = 2.4; // will be rounded off to nearest integer 2integer r6 = 2.8; // will be rounded off to nearest integer 3integer r7 = 2.5; // will be rounded off to 3

always_comb

“_” A separator to improve readability.

’x’, ’X’ Unknown value.

’z’, ’Z’, ’?’ Tri-state value.

334 32 bits wide decimal number

32’b101 32 bits wide binary number (zero leftfilled)

3’b011 3 bits wide binary number (i.e. 011)

20’h’f_ffff 20 bits wide hexadecimal number

10’bZ 10 bits wide all tri-state

Page 130: PrecisionRTL Style

Precision Synthesis Style Guide, 2011a Update2130

SystemVerilog Language FeaturesBasic Language Constructs

November 2011

begin................endendmodule

String Literals of type packed arrays

Examplebyte c1 = "A" ;bit [0:1] [7:0] c2 = "ab";byte c3 = "";

Array Literals

Exampleint n[0:1][0:2] = {{0,1,2},{3{4}}};int n1[0:1][0:5] = {2{{3{4, 5}}}};int n2[0:2] = {1:1, default:0};

Data TypesSystemVerilog data types supported by Precision Synthesis include:

• Integer (integer, int, shortint, longint, byte, logic, bit, reg)

• Void

• User Defined Types

• Enumerations

• Structures (packed/unpacked) and Unions (packed)

Precision Synthesis does not support the following data types:

• Real and Short Real

• Chandle

• String

• Event

• Union (unpacked)

• Tagged Union

• Class

Page 131: PrecisionRTL Style

SystemVerilog Language FeaturesBasic Language Constructs

Precision Synthesis Style Guide, 2011a Update2 131November 2011

Some of these data types (bit,reg,logic) can take an optional range specification as a means ofcreating a bit vector. The range expression is of the following form:

Some of these data types are used in the example below, along with the range expression syntax.More details on the data types are presented in the following sections.

[<most significant bit> : <least significant bit>]

// This design implements a Manchester Encoder//module manenc (reset, clk , data , load , sdata, ready);parameter max_count = 7;

input clk, load;input [max_count:0] data;output sdata, ready ;

reg sdata, ready ;reg [2:0] count;reg [max_count:0] sout;reg phase;

// Phase encodingalways @ (posedge clk)

beginsdata = sout[max_count] ^ phase;phase = ~phase ;

end

Page 132: PrecisionRTL Style

Precision Synthesis Style Guide, 2011a Update2132

SystemVerilog Language FeaturesBasic Language Constructs

November 2011

Integer Data Types

Shortint

shortint (2-state SystemVerilog data type, 16 bit signed integer)

Exampleshortint a = 5’d10;

Int

int (2-state SystemVerilog data type, 32 bit signed integer)

Exampleint a = -10;

Longint

longint (2-state SystemVerilog data type, 64 bit signed integer)

Examplelongint a;

// Shift dataalways @ (posedge phase)

beginif ((count == 0) & !load) begin

sout[max_count:1] = sout[0:max_count - 1];sout[0] = 1’b0;ready = 1’b1;

endelse if ((count == 0) & load ) begin

sout = data;count = count + 1;ready = 1’b0;

endelse if (count == max_count) begin

sout[max_count:1] = sout[0:max_count - 1];sout[0]= 1’b0;count = 0;

endelse begin

sout[max_count:1] = sout[0:max_count - 1];sout[0]= 1’b0;count = count + 1;

endend

endmodule

Page 133: PrecisionRTL Style

SystemVerilog Language FeaturesBasic Language Constructs

Precision Synthesis Style Guide, 2011a Update2 133November 2011

Byte

byte (2-state SystemVerilog data type, 8 bit signed integer or ASCII character)

Examplebyte a = -2’b10;

Bit

bit (2-state SystemVerilog data type, user-defined vectorsize)

Examplebit a = 1’b0;

Logic

logic (4-state SystemVerilog data type, user-defined vector size)

Examplelogic [1:0]a = 2’bx1;

Reg

reg (4-state Verilog-2001 data type, user-defined vector size)

Examplereg a = 1’bz;

Integer

integer (4-state Verilog-2001 data type,32 bit signed integer)

Exampleinteger a = -10;

User Defined Types

Examplemodule userdeftypes;

typedef bit my_bit;my_bit b ;

endmodule

Page 134: PrecisionRTL Style

Precision Synthesis Style Guide, 2011a Update2134

SystemVerilog Language FeaturesBasic Language Constructs

November 2011

EnumerationsEnum datatype is of type int unless specified otherwise.

Exampleenum {WAIT, LOAD, STORE} state;//This is of type int. i.e. 32 bit signed

enum bit [2:0]{A, B, C, D, E, F} var_enum;//This is of type bit [2:0]

Users can also define types using enum.

Exampletypedef enum bit [2:0]{A, B, C, D, E, F} type_enum;type_enum var_enum;

Structures (packed/unpacked) and Unions (packed)Packed Structures can be declared as follows. Each element of packed structure must be ofpacked type.

Examplestruct packed{ logic field0; int field1; bit [7:0] field2; } st_var;

Unpacked structures may have unpacked elements.

Examplestrcut{ int field0[1:0]; reg [3:0] field1[3:0]; bit [7:0] field2; } st_upkd_var;

Packed union can be declared as follows: Each Element of the packed union must be packed

and the width of each element of packed union must be the same.

Exampleunion packed{ logic [7:0] field0; byte field1; bit [7:0] field2; } un_var;

Page 135: PrecisionRTL Style

SystemVerilog Language FeaturesBasic Language Constructs

Precision Synthesis Style Guide, 2011a Update2 135November 2011

Castingint’(2.0 * 3.0);shortint’{8’hFA,8’hCE};

A decimal number as a data type means a number of bits.

17’(x - 2);

The signedness can also be changed.

signed’(x);

Examplemodule test1();

typedef logic [3:0] l3;typedef logic l4 [3:0] ;

l3 var1;int in1,in2;alwaysbegin in1 = 9; var1 = l3’ (in1); // var1 = 1001 in2 = signed’ (var1); // in2 = -7 in2 = in1 + signed’(var1); // 9-7 = 2endendmodule

Arrays

Packed and Unpacked Arraysbit [7:0] c1; // packed arraylogic u [7:0]; // unpacked array

Examplemodule array1();

bit signed [15:0] array ;shortint a,b ;int intarr1[2][3];

alwaysbeginarray = -2’b10 ;a = array[7:0] ;b = array ;endendmodule

Page 136: PrecisionRTL Style

Precision Synthesis Style Guide, 2011a Update2136

SystemVerilog Language FeaturesBasic Language Constructs

November 2011

Multi-dimensioned Arraysbit [1:5] [1:6] foo4 [1:7] [1:8];// 1 to 6 varies most rapidly, followed

// by 1 to 5, then 1 to 8 and then 1 to 7

Example//declarationmodule mdarray1();

bit [7:0] md [1:2] ; // 2 entries (unpacked) of one byte (packed)

alwaysbegin //usage md[1] = "A" ; md[2] = "B" ;endendmodule

Enhancement over Verilog-2001 is support for multiple packed dimensions.

Examplelogic [1:0][2:0][3:0] l1;bit [5:0][3:0]b1;

Multiple unpacked dimensions can also be defined in stages with typedef.

Examplemodule mdarray2();

typedef bit[1:5] bsix; //packed arraybsix [1:0] memten; //1 to 5 varies most rapidly

typedef bit ubsix [1:5] ; //unpacked arrayubsix umemten [1:0] ;

alwaysbegin memten[1] = 5’b10100; umemten[0][1] = 1’b1;endendmodule

Out of range index values will generate an Error for both reading from and writing to an array.

Indexing and Slicing of ArraysPrecision Synthesis will allow selection of one or more contiguous elements using a slicename.An single element of a packed or unpacked array can be selected using an indexed name.

Indexing and Slicing of an array with single packed dimension and with multiple unpackeddimensions.

Page 137: PrecisionRTL Style

SystemVerilog Language FeaturesBasic Language Constructs

Precision Synthesis Style Guide, 2011a Update2 137November 2011

Packed Example//packed dim//no. 1 2 3logic [1:0][2:0][3:0]l1;l1[1] = 12’d5; //indexing Packed Dim 1l1[1:0] = 24’d15; //slicing Packed Dim 1l1[1][0] = 4’d5; //indexing Packed Dim 2l1[1][1:0] = 8’d9;//slicing Packed Dim 2l1[1][2][1:0] = 3’b101;//slicing Packed Dim 3

Indexing and Slicing of any packed Multi-Dimension array is also supported.

Unpacked Examplemodule slice1();

//declarations

bit [3:0] [7:0] j;

bit [3:0]uj [7:0] ;byte k ;

bit [31:0] busA [7:0];int busB [1:0];

alwaysbegin

//usagej[3] = "A";j[2:0] = "ABC" ;j[1][3:0] = 4’d3;

busB = busA[7:6] ;busA[3:2] = busB;

uj[3] = "A";// uj[2:0] = "ABC" ; // erroruj[1][3:0] = 4’d3;

end....................endmodule

Array AssignmentPrecision will type check following two things during array assignment:

1. Source and target are both arrays, with the same number of unpacked dimensions.

2. The length of each unpacked dimension is the same.

Page 138: PrecisionRTL Style

Precision Synthesis Style Guide, 2011a Update2138

SystemVerilog Language FeaturesBasic Language Constructs

November 2011

Exampleint A[10:1]; // fixed-size array of 10 elementsint B[0:9]; // fixed-size array of 10 elementsint C[24:1]; // fixed-size array of 24 elementsA = B; // ok. Compatible type and same sizeA = C; // type check error: different sizes

Arrays as Arguments

Examplemodule arrayarg(in,out);input int in[1:2][0:1];output int out;int temp1[1:2][0:2];int temp2[1:2];reg temp3[1:2][0:1];

function int argfunc (int inf[0:1][0:1]) ;argfunc = inf[0][0];endfunction

always begin

out = argfunc(in); //ok same type and dimension //out = argfunc(temp1); //error incompatible size //out = argfunc(temp2); //error incompatible dimension //out = argfunc(temp3); //error incompatible type

end

endmodule

Data Declarations

ConstantsConstants are named data items which never change.

A constant declared with the const keyword, can only be set to an expression of literals,parameters, local parameters, genvars, a constant function of these, or other constants. This isalso supported in Precision Synthesis.

Exampleconst logic c1 = 1’b1;

Page 139: PrecisionRTL Style

SystemVerilog Language FeaturesBasic Language Constructs

Precision Synthesis Style Guide, 2011a Update2 139November 2011

Attributes

Default Attribute TypeThe default type of an attribute with no value is bit, with a value of 1. Otherwise, the attributetakes the type of the expression.

Operators and Expressions

Assignment OperatorsPrecision Synthesis will support all new assignment operators introduced in SystemVerilog -3.1, such as +=,-=, *=, /=, %=, &=, |=, <<=, >>=, <<<=, >>>= and the increment and decrementoperators, ++ and --.

All Operators are of fixed type and size.

Exampleint a;a += 2; // a = a + 2;a *= 3; // a = a * 3;a--; // a = a - 1;

Procedural Statements and Control flow

Selection StatementsPrecision Synthesis supports the keywords unique and priority, which can be used before an ifor case statement.

A priority if indicates that a series of if...else...if conditions shall be evaluated in the orderlisted.

Examplemodule prioritytest(in1, in2, in3, cond, out);input in1, in2, in3 ;input [1:0]cond;output out;reg out;

always@(in1, in2, in3, cond)begin priority if(cond[1] == 1’b1) out = in1; else if(cond[0] == 1’b0) out = in2; else

Page 140: PrecisionRTL Style

Precision Synthesis Style Guide, 2011a Update2140

SystemVerilog Language FeaturesBasic Language Constructs

November 2011

out = in3;endendmodule

Examplemodule prioritycase1(in, cond, out);input in ;input [1:0] cond;output reg [2:0] out;always@(in, cond) begin priority casex(cond) 2’b00: out =1; 2’b0x: out = in; 2’b11: out =0; default: out = in; endcase endendmodule

Examplemodule uniquecase1(in, cond, out);input in ;input [1:0]cond;output reg [2:0] out;always@(in, cond) begin unique casex(cond) 2’b00: out =1; 2’b01: out = in; 2’b11: out =0; default: out = in; endcase endendmodule

Loop Statements

The Do While LoopPrecision Synthesis supports SystemVerilog Do...While loop structures.

do { statement } while(condition);

Examplemodule dowhiletest(out, in);

Page 141: PrecisionRTL Style

SystemVerilog Language FeaturesBasic Language Constructs

Precision Synthesis Style Guide, 2011a Update2 141November 2011

input [9:0] in; output [9:0] out; reg [9:0] out; integer i; reg [9:0] temp; always@( in ) begin i = 0; temp = 0; out = 0; do begin temp[i] = in[i]; i=i+1; end while ( (i<2) ); out = temp; endendmodule

Enhanced For Loop

Examplemodule fortest1(out,out1, in1,in2,clk);output reg [2:0]out;output reg [2:0]out1;input [5:0]in1,in2,clk;reg [2:0]temp;integer j,k,i;

always@(clk,in1)begintemp = in1; for(integer i=0,k=0,j=0;i<3;i=i+1,k=k+1) begin out[j]=temp[j]; temp[i]=temp[i]+1; out[k]=temp[k]+1; out1[k]=in1[j] & in2; end out =temp; //out1=j;endendmodule

Jump Statements (Break, Continue and Return)Precision Synthesis supports the following four SystemVerilog jump statements.

1. break -> out of loop

2. continue -> skip to end of loop

3. return expression -> exit from a function

Page 142: PrecisionRTL Style

Precision Synthesis Style Guide, 2011a Update2142

SystemVerilog Language FeaturesBasic Language Constructs

November 2011

4. return -> exit from a task or void function

Return Examplemodule returntest(in1,in2,cond,out1);input [1:0] in1,in2,cond;output [1:0] out1;reg [1:0] out1;

function [1:0] function1;input [1:0] in1,in2,cond; if(cond==2’b00) return in1|in2;// use of return else function1 = in1 ~^ in2;endfunction

always @(in1 or in2 or cond) begin out1 = function1(in1,in2,cond); endendmodule

Similarly Break and Continue can be used inside a While, Do-While, Repeat or Forever loop:

module for2(out );//input [9:0] in;output [9:0] out;reg [9:0] out;reg [9:0] in;

integer i;reg [9:0] temp;reg a, b;always@( in )begin in = 2’b01; temp = 0; out = 0; for(i=0 ; i<5 ;i=i+1) // flag1 begin temp[i] = i; if( (i<2 ) ) continue;// disable flag1 else break;// disable flag2 end // flag2 out = temp;endendmodule

Page 143: PrecisionRTL Style

SystemVerilog Language FeaturesBasic Language Constructs

Precision Synthesis Style Guide, 2011a Update2 143November 2011

Named BlocksThe Block name is specified after a Begin statement and is preceded by a colon.

Precision Synthesis will allow a matching Block name (optional) to be specified after the blockend.

Examplemodule namedblock(input reg in1 , in2, output reg out);always @(in1 or in2)begin : label1 out = in1 + in2;end : label1

endmodule

Precision Synthesis will issue a “Block name mismatch” error if the Begin and End names donot match:

begin : label1 out = in1 + in2;end : label2 //mismatch

Processes

Combinatorial Logic

Examplemodule comb_logic(in1,in2,out);input int in1,in2;output int out;int w;

always_combout <=in1 & in2;

always_combw <=in1 | in2;

endmodule

Precision Synthesis will give a warning message if the logic inside always_comb is not purelycombinational.

Examplemodule latch(sel,data,out);input sel;input byte data;output [7:0]out;

Page 144: PrecisionRTL Style

Precision Synthesis Style Guide, 2011a Update2144

SystemVerilog Language FeaturesBasic Language Constructs

November 2011

logic [7:0]out;

always_combbegin if(sel == 1’b0) out = data;endendmodule

Warning: Latch inferred for net out[7] inside always_comb block

Latched Logic

Examplemodule latch_logic(in1,in2,out);input in1,in2;output out;reg out;reg w;

always_latchif(in1)

out<=in1;

always_latchif(in2)

w<=in2;

endmodule

If latch is not inferred inside always_latch then Precision Synthesis will give a Warningmessage.

Sequential Logic

Examplemodule ff(in1,in2,out);

input in1,in2;output out;

reg d,out;reg clk,reset;

always_ffbegin@(changed clk or negedge reset) if(! reset) out <= 0; else out <= d;end

endmodule

Page 145: PrecisionRTL Style

SystemVerilog Language FeaturesBasic Language Constructs

Precision Synthesis Style Guide, 2011a Update2 145November 2011

Tasks and FunctionsPrecision Synthesis supports the following additions for tasks and functions.

1. Default direction will be input if no direction is specified.

2. Default data type will be logic if no data type is specified.

3. Returning from a task or function before reaching the end.

4. Support for output port and inout port in functions.

5. Passing Argument values by name instead of position.

6. Default argument values.

7. Allowing arrays as formal argument to the tasks/functions.

Task

Examplemodule taskfunc(input int in1,in2,input bit clk,output int out1,out2);always @*begin

task1(in1,in2,clk,out1);endtask task1(input [7:0] in1, in2,input clk,output int out1);

reg [3:0][7:0] temp;begintemp[0] <= in1 + in2;out1 <= temp;

endendtaskendmodule

Function

Examplemodule taskfunct1(input int in1,in2,sel,output int out1,out2);always_combbegin

out2 = fun1(in1,in2,sel,out1);endfunction [7:0] fun1(input [7:0] in1, in2,input [1:0] sel,output int out1);reg [1:0][7:0] temp;begin

temp[0] = in1 + in2;temp[1] = in1 - in2;out1 = temp;if (sel == 2’b00)

return temp[0];else if (sel == 2’b01)

return temp[1];

Page 146: PrecisionRTL Style

Precision Synthesis Style Guide, 2011a Update2146

SystemVerilog Language FeaturesBasic Language Constructs

November 2011

endendfunctionendmodule

Void FunctionsReturn value of functions can be ignored by casting the function to void type.

void’(some_function());

Default Argument Value

Examplemodule addVal(input byte in1, in2, output byte out1,out2);always_combbeginadd1(in1, ,out1);// equivalent to add1(in1,1,out);

add1(, in2,out1);// equivalent to add1(0,in2,out);out2 = add2(in1,);// equivalent to out2 = add2(in1,1);out2 = add2(,in2);// equivalent to out2 = add2(0,in2);

endtask add1(input byte in1 = 0, in2 = 1,output byte out);

out = in1 + in2;endtask//function definition with default arg. values.function byte add2(input byte in1 = 0, in2 = 1);

add2 = in1 + in2;endfunctionendmodule

Argument Passing by Namemodule taskfunct3(input int in1,in2,sel,output int out1,out2);always_combbegin out2 = fun1(.in1(in1),.in2(in2),.sel(sel),.out1(out1));endfunction [7:0] fun1(input [7:0] in1, in2,input sel,output int out1);begin out1 = in1 + in2; if(sel == 1’b0) return in1; else return in2; endendfunctionendmodule

Page 147: PrecisionRTL Style

SystemVerilog Language FeaturesBasic Language Constructs

Precision Synthesis Style Guide, 2011a Update2 147November 2011

Hierarchy

Port DeclarationsPrecision Synthesis will allow Port as a declaration of a net, or a variable of any type, includingan array. There is language support for all basic types (such as, shortint, longint, int, bit, logic,byte) as ports, and for arrays, struct, union and interface as ports.

Examplemodule portdecl (in1,in2,out); typedef struct { bit isfloat; union packed{ int i; int f; } n; } tagged_t; // named structure

input int in1; input logic in2; output tagged_t out;endmodule

NotePrecision Synthesis does not support port as a declaration of an event.

Port Connection Rules for new SystemVerilog Data Types

Instantiation Using Implicit .name Port ConnectionsPrecision Synthesis will allow the capability to implicitly instantiate ports using a .name syntaxif the instance-port name and size match the connecting variable-port name and size.

Examplemodule alu (output reg [7:0] alu_out,output reg zero,input [7:0] ain, bin,input [2:0] opcode);// RTL code for the alu moduleendmodule

module alu_accum3 (output [15:0] dataout,input [7:0] ain, bin,input [2:0] opcode,input clk, rst_n);wire [7:0] alu_out;

alu alu (.alu_out, .zero(), .ain, .bin, .opcode);endmodule

Page 148: PrecisionRTL Style

Precision Synthesis Style Guide, 2011a Update2148

SystemVerilog Language FeaturesBasic Language Constructs

November 2011

Instantiation Using Implicit .* Port Connections

Examplemodule alu_accum4 (output [15:0] dataout,input [7:0] ain, bin,input [2:0] opcode,input clk, rst_n);wire [7:0] alu_out;alu alu (.*, .zero());endmodule

Interfaces

Example/*------------------------------------------------------------------------- Copyright (c) 2006 Mentor Graphics Corporation. All rights reserved.-- The following information has been generated by Mentor Graphics-- and may be freely distributed and modified.---- Design Module : top, memory---- Purpose : This design shows how the interface feature can he used to-- bundle and reuse I/O among different modules in the design.-- It also illustrates how modport is used to define port-- directions.---- The following new constructs in SV are used:-- - interface, typedef, always_comb------ Version: 1.0-- Precision: 2005c-- Date: Dec 23 2005-----------------------------------------------------------------------*/

interface address_bus; parameter p1 = 7; wire [p1:0] read_address; wire [p1:0] write_address; modport address_port_in (input read_address, input write_address);endinterface

interface data_bus; parameter p2 = 7; wire [p2:0] data_in; wire [p2:0] data_out; modport data_port (input data_in, output data_out);endinterface

interface control_bus; wire reset; wire clk;

Page 149: PrecisionRTL Style

SystemVerilog Language FeaturesBasic Language Constructs

Precision Synthesis Style Guide, 2011a Update2 149November 2011

wire wren; wire ren;

modport memory_control (input reset, input clk, input wren, input ren);endinterface

//-----------------------------------------------------

module memory (address_bus.address_port_in addr, control_bus.memory_control ctrl, data_bus.data_port data);parameter p1 =7;parameter p2 =7;

typedef logic [7:0] BYTE;BYTE memory[(2*p1+1):0][(2*p1+1):0];BYTE latch;

assign data.data_out = latch;

always @ (posedge ctrl.clk)begin if(ctrl.reset) begin for(int i = (2*p1+1); i >= 0; i--) begin for(int j = (2*p1+1); j >= 0; j--) begin memory[i][j] = ‘0; end end latch = ‘0; end else begin if(ctrl.ren) begin latch = memory[addr.read_address[3:0]][addr.read_address[7:4]]; end if(ctrl.wren) begin memory[addr.write_address[3:0]] [addr.write_address[7:4]] = data.data_in; end endendendmodule

//-----------------------------------------------------

module top (clk, reset, wren, ren, raddr, waddr, wdata, rdata);parameter p1 =7;parameter p2 =7;

input clk;input reset;input wren;input ren;input [p1:0] raddr;

Page 150: PrecisionRTL Style

Precision Synthesis Style Guide, 2011a Update2150

SystemVerilog Language FeaturesBasic Language Constructs

November 2011

input [p1:0] waddr;input [p2:0] wdata;output [p2:0] rdata;logic [p2:0] rdata;

// Instantiate interfacesaddress_bus #(.p1(p1)) addr();data_bus #(.p2(p2)) data();control_bus ctrl();

// Instantiate memory modulememory #(.p1(p1), .p2(p2)) mem_i (.*);

assign ctrl.clk = clk;assign ctrl.reset = reset;assign ctrl.wren = wren;assign ctrl.ren = ren;assign addr.read_address = raddr;assign addr.write_address = waddr;assign data.data_in = wdata;

always_combbegin rdata = data.data_out;endendmodule

Compiler Directives

`Define MacroIn SystemVerilog, the macro can include ‘", ‘\’" and ‘‘.

An ‘" overrides the usual lexical meaning of ", and indicates that the expansion should includean actual quotation mark.

A ‘\’" indicates that the expansion should include the escape sequence \”.

A ‘‘ delimits lexical tokens without introducing white space, allowing identifiers to beconstructed from arguments.

Example`define foo(f) f‘‘_suffix//This expands: foo(bar)to:bar_suffix.

Unpacked Array ConcatenationUnpacked array concatenation provides a flexible way to populate an unpacked array using acollection of elements and arrays. An unpacked array concatenation can appear as the source

Page 151: PrecisionRTL Style

SystemVerilog Language FeaturesBasic Language Constructs

Precision Synthesis Style Guide, 2011a Update2 151November 2011

expression in an assignment-like context. It cannot appear in any other context. The target ofsuch an assignment-like context is an array whose slowest-varying dimension is an unpackedfixed-size.

Exampleint A3[1:3];assign A3 = {1,2,3};

module top (clk, in1, in2, out);parameter type T = logic;input T clk;input T [0:3] in1,in2;output T [31:0] out;T [0:7] u [0:3];T [0:3] t [0:0] [0:1];

assign t[0][0] = in1;assign t[0][1] = in1;assign out[31:0] = {u[0],u[1],u[2],u[3]};

always @(posedge clk)begin u = {t[0],in1,in2};endendmodule

Foreach Loop SupportThe foreach loop construct specifies iterations over the elements of an array. Its argument is anidentifier that designates any type of array followed by a comma-separated list of loop variablesenclosed in square brackets. Each loop variable corresponds to one of the dimensions of thearray.

Exampleint prod [1:8] [1:3];foreach( prod[ k, m ] ) prod[k][m] = k * m; // initialize

Removing Text Substitution MacrosThe `undefineall directive removes definitions for all text macros previously defined by the`define compiler directive within the compilation unit. The directive specification does notaffect built-in macros

Example`undefineall // remove any user macros from other files

Page 152: PrecisionRTL Style

Precision Synthesis Style Guide, 2011a Update2152

SystemVerilog Language FeaturesExample Designs

November 2011

Set Membership Operator (Inside Operator)The Inside Operator checks for the set membership of any expression by scanning through thelist of expressions or ranges specified as sets. It returns 1'b1 if the match is found and 1'b0

otherwise. The Inside Operator uses the equality operator (==) for non-integral expressions andthe wildcard equality operator (?=) for integral expressions.

Examplelogic [2:0] val;while ( val inside {3'b1?1} ) ...// matches 3'b101, 3'b111, 3'b1x1, 3'b1z1

Example DesignsThe following table provides a brief description of the examples in this section. The code filesare available in the Precision Synthesis software tree in the following directory:

<precision_install_dir>/shared/examples/style_guide_hdl/SystemVerilog

Table 4-2. SystemVerilog Examples

Example Description

ALU This design is a generic ALU design utilizing these SystemVerilogconstructs: struct, union, always_comb, typedef, priority case.

Counter This design is a parameterized counter utilizing these SystemVerilogconstructs: union, and typedef enum.

FSM 1 This design shows how mixed constructs between Verilog-2001 andSV are used within the same FSM design. The SystemVerilogconstructs used are: union, typedef enum, unique case, always_ff,always_comb.

FSM 2 This design shows how Verilog-2001 and SystemVerilog union,typedef enum, unique case, and always_ff can be combined in thesame FSM design.

FSM 3 This design shows how typedef enum, union, unique case, andalways_ff are used an arbiter design.

FSM Reencoded This example uses the classic traffic light control design to illustrateconst, enum, unique case, always_ff, always_comb elements, andFSM state encoding override by an applied synthesis pragma.

Interface This design uses the SystemVerilog interface feature to bundle andreuse I/O among different modules in the design. Modport is used todefine port direction.

Page 153: PrecisionRTL Style

SystemVerilog Language FeaturesExample Designs

Precision Synthesis Style Guide, 2011a Update2 153November 2011

ALUThis design is a generic ALU design utilizing these SystemVerilog constructs: struct, union,always_comb, typedef, priority case.

Example 4-1. SystemVerilog ALU

/*------------------------------------------------------------------------- Copyright (c) 2006 Mentor Graphics Corporation. All rights reserved.-- The following information has been generated by Mentor Graphics-- and may be freely distributed and modified.---- Design name : ALU---- Purpose : This design is a generic ALU design coded in SystemVerilog-- The following new constructs in SV are used:-- - struct-- - union-- - always_comb-- - typedef-- - priority case---- Rev: 1.0-- Precision: 2005c-- Date: Dec 23 2005-----------------------------------------------------------------------*/

module ALU(inp_pack, out);

typedef enum bit[1:0] {ADD, SUB, SL, SR} instruction;

typedef union packed { shortint signed in1; shortint unsigned in2; }inp;

typedef union packed { int signed out1; int unsigned out2; }out_vec;

typedef enum bit {SIGN, UNSIGN} operation;

typedef struct packed { inp in1, in2; instruction instr; operation op; }input_packet;

input input_packet inp_pack;output out_vec out;

always_comb beginpriority case(inp_pack.instr) ADD : beginif(inp_pack.op == SIGN)

Page 154: PrecisionRTL Style

Precision Synthesis Style Guide, 2011a Update2154

SystemVerilog Language FeaturesExample Designs

November 2011

out.out1 = inp_pack.in1.in1 + inp_pack.in2.in1; else out.out2 = inp_pack.in1.in2 + inp_pack.in2.in2; end SUB : beginif(inp_pack.op == SIGN) out.out1 = inp_pack.in1.in1 - inp_pack.in2.in1; else out.out2 = inp_pack.in1.in2 - inp_pack.in2.in2; end SL : beginif(inp_pack.op == SIGN) out.out1 = inp_pack.in1.in1 << inp_pack.in2.in1; else out.out2 = inp_pack.in1.in2 << inp_pack.in2.in2; end SR : beginif(inp_pack.op == SIGN) out.out1 = inp_pack.in1.in1 >> inp_pack.in2.in1; else out.out2 = inp_pack.in1.in2 >> inp_pack.in2.in2; end default: begin out.out1 = 0; out.out2 = 0; endendcaseendendmodule

CounterThis design is a parameterized counter utilizing these SystemVerilog constructs: union, andtypedef enum.

Example 4-2. SystemVerilog Counter

/*------------------------------------------------------------------------- Copyright (c) 2006 Mentor Graphics Corporation. All rights reserved.-- The following information has been generated by Mentor Graphics-- and may be freely distributed and modified.---- Design name : counter---- Purpose : This design is a parameterized counter design coded in-- SystemVerilog. The design can be counted in either binary-- or decimal mode.-- - if mode is 1 then counter operates in binary mode-- - if mode is 0 then counter operates in decimal mode-- - if incdec is 1 then it increments-- - if incdec is 0 then it decrements---- The following new constructs in SV are used:-- - union-- - typedef enum

Page 155: PrecisionRTL Style

SystemVerilog Language FeaturesExample Designs

Precision Synthesis Style Guide, 2011a Update2 155November 2011

---- Rev: 1.0-- Precision: 2005c-- Date: Dec 23 2005-----------------------------------------------------------------------*/

module counter (mode,incdec,reset,clk,out);input reset,clk;input mode,incdec;output [2:0] out;

localparam BINARY = 1;localparam STEP = 1;typedef enum logic [2:0] {state[8]} binary_type;typedef enum logic [2:0] {gray0 = 3’b000,gray1 = 3’b001, gray2 =3’b011,gray3 = 3’b010, gray4 = 3’b110,gray5 = 3’b111, gray6 =3’b101,gray7 = 3’b100 } gray_type;

union packed{ binary_type binary_count; gray_type gray_count;}cs;

assign out = cs;always @(posedge clk or negedge reset)begin if(!reset) begin if(mode == BINARY) cs.binary_count <= cs.binary_count.first(); else cs.gray_count <= cs.gray_count.first(); end else begin if(mode == BINARY) if(incdec) cs.binary_count <= cs.binary_count.next(STEP); else cs.binary_count <= cs.binary_count.prev(STEP); else if(incdec) cs.gray_count <= cs.gray_count.next(STEP); else cs.gray_count <= cs.gray_count.prev(STEP); endendendmodule

Page 156: PrecisionRTL Style

Precision Synthesis Style Guide, 2011a Update2156

SystemVerilog Language FeaturesExample Designs

November 2011

FSM 1This design shows how mixed constructs between Verilog-2001 and SV are used within thesame FSM design. The SystemVerilog constructs used are: union, typedef enum, unique case,always_ff, always_comb.

Example 4-3. SystemVerilog FSM 1

/*------------------------------------------------------------------------- Copyright (c) 2006 Mentor Graphics Corporation. All rights reserved.-- The following information has been generated by Mentor Graphics-- and may be freely distributed and modified.---- Design Module : FSM, encoder, decoder---- Purpose : This design shows how typedef enum can be coded using SV and-- how mixed constructs between Verilog-2001 and SV are used-- within the same design.---- The following new constructs in SV are used:-- - union, typedef enum, unique case, always_ff, always_comb------ Version: 1.0-- Precision: 2005c-- Date: Dec 23 2005-----------------------------------------------------------------------*/

module FSM( input bit [7:0] in, input bit clk, reset, output bit [7:0] out_encoded, out_decoded);

bit [7:0] intermediate;typedef enum bit[3:0] {s0 = 4’b0000, s1 = 4’b0001, s2 = 4’b0010, s3 = 4’b0011, s4 = 4’b0100, s5 = 4’b0101, s6 = 4’b0110, s7 = 4’b0111, s8 = 4’b1000, s9 = 4’b1001, s10 = 4’b1010, s11 = 4’b1011, s12 = 4’b1100, s13 = 4’b1101, s14 = 4’b1110, s15 = 4’b1111} STATE;STATE current_state;

encode a(in, current_state, out_encoded); decode b(intermediate, current_state, out_decoded);

assign intermediate = out_encoded;

always_ff @ (posedge clk)begin if(reset) current_state <= current_state.first(); else current_state <= current_state.next();endendmodule

//======================================

Page 157: PrecisionRTL Style

SystemVerilog Language FeaturesExample Designs

Precision Synthesis Style Guide, 2011a Update2 157November 2011

module encode ( input bit [7:0] in, input bit [3:0] current_state, output bit [7:0] out_encoded);

bit [7:0] lock;assign out_encoded = in ^ lock;

always_combbegin unique case (current_state) 0000: lock = {7{current_state[0]}}; 0001: lock = {7{current_state[0]}}; 0010: lock = {7{current_state[0]}}; 0011: lock = {7{current_state[0]}}; 0100: lock = {7{current_state[1]}}; 0101: lock = {7{current_state[1]}}; 0110: lock = {7{current_state[1]}}; 0111: lock = {7{current_state[1]}}; 1000: lock = {7{current_state[2]}}; 1001: lock = {7{current_state[2]}}; 1010: lock = {7{current_state[2]}}; 1011: lock = {7{current_state[2]}}; 1100: lock = {7{current_state[3]}}; 1101: lock = {7{current_state[3]}}; 1110: lock = {7{current_state[3]}}; 1111: lock = {7{current_state[3]}}; default: lock = 8’b0; endcaseendendmodule//======================================

module decode (input bit [7:0] in, input bit [3:0] current_state, output bit [7:0] out_decoded);

bit [7:0] key;bit [7:0] temprary;bit [7:0] decoded;

assign out_decoded = decoded;

always_combbegin unique case (current_state) 0000: key = {7{current_state[0]}}; 0001: key = {7{current_state[0]}}; 0010: key = {7{current_state[0]}}; 0011: key = {7{current_state[0]}}; 0100: key = {7{current_state[1]}}; 0101: key = {7{current_state[1]}}; 0110: key = {7{current_state[1]}}; 0111: key = {7{current_state[1]}}; 1000: key = {7{current_state[2]}}; 1001: key = {7{current_state[2]}}; 1010: key = {7{current_state[2]}}; 1011: key = {7{current_state[2]}}; 1100: key = {7{current_state[3]}};

Page 158: PrecisionRTL Style

Precision Synthesis Style Guide, 2011a Update2158

SystemVerilog Language FeaturesExample Designs

November 2011

1101: key = {7{current_state[3]}}; 1110: key = {7{current_state[3]}}; 1111: key = {7{current_state[3]}}; default: key = 8’b0; endcase

for(int i = 0; i < 8; i++) begin if(in[i] == 1’b1) decoded[i] = ~key[i]; else decoded[i] = key[i]; endendendmodule//======================================

FSM 2This design shows how Verilog-2001 and SystemVerilog union, typedef enum, unique case,and always_ff can be combined in the same FSM design.

Example 4-4. SystemVerilog FSM 2

/*------------------------------------------------------------------------- Copyright (c) 2006 Mentor Graphics Corporation. All rights reserved.-- The following information has been generated by Mentor Graphics-- and may be freely distributed and modified.---- Design Module : FSM, encoder, decoder---- Purpose : This design shows how typedef enum can be coded using SV and-- how mixed constructs between Verilog-2001 and SV are used-- within the same design---- The following new constructs in SV are used:-- - union, typedef enum, unique case, always_ff------ Version: 1.0-- Precision: 2005c-- Date: Dec 23 2005-----------------------------------------------------------------------*/module FSM2( in, reset, clk, out_encoded, out_decoded);input bit [7:0] in;input bit clk;input bit reset;output bit [7:0] out_encoded;output bit [7:0] out_decoded;

bit [7:0] intermediate;

typedef enum bit[3:0] {s0 = 4’b0000, s1 = 4’b0001, s2 = 4’b0010, s3 = 4’b0011, s4 = 4’b0100, s5 = 4’b0101, s6 = 4’b0110, s7 = 4’b0111, s8 = 4’b1000,

Page 159: PrecisionRTL Style

SystemVerilog Language FeaturesExample Designs

Precision Synthesis Style Guide, 2011a Update2 159November 2011

s9 = 4’b1001, s10 = 4’b1010, s11 = 4’b1011, s12 = 4’b1100, s13 = 4’b1101, s14 = 4’b1110, s15 = 4’b1111} STATE;STATE current_state;

encode a(in, current_state, out_encoded); decode b(intermediate, current_state, out_decoded);

assign intermediate = out_encoded;

always_ff @ (posedge clk)begin if(reset) current_state = current_state.first(); else current_state = current_state.next();endendmodule

//======================================

module encoder ( input bit [7:0] in, input bit [3:0] current_state, output bit [7:0] out_encoded);

bit [7:0] lock;assign out_encoded = in ^ lock;

always @*begin unique case (current_state) 0000: lock = {7{current_state[0]}}; 0001: lock = {7{current_state[0]}}; 0010: lock = {7{current_state[0]}}; 0011: lock = {7{current_state[0]}}; 0100: lock = {7{current_state[1]}}; 0101: lock = {7{current_state[1]}}; 0110: lock = {7{current_state[1]}}; 0111: lock = {7{current_state[1]}}; 1000: lock = {7{current_state[2]}}; 1001: lock = {7{current_state[2]}}; 1010: lock = {7{current_state[2]}}; 1011: lock = {7{current_state[2]}}; 1100: lock = {7{current_state[3]}}; 1101: lock = {7{current_state[3]}}; 1110: lock = {7{current_state[3]}}; 1111: lock = {7{current_state[3]}}; default: lock = 8’b0; endcase

endendmodule

//======================================

module decoder (input bit [7:0] in, input bit [3:0] current_state, output bit [7:0] out_decoded);

Page 160: PrecisionRTL Style

Precision Synthesis Style Guide, 2011a Update2160

SystemVerilog Language FeaturesExample Designs

November 2011

bit [7:0] key;bit [7:0] decoded;

assign out_decoded = decoded;

always @*begin unique case (current_state) 0000: key = {7{current_state[0]}}; 0001: key = {7{current_state[0]}}; 0010: key = {7{current_state[0]}}; 0011: key = {7{current_state[0]}}; 0100: key = {7{current_state[1]}}; 0101: key = {7{current_state[1]}}; 0110: key = {7{current_state[1]}}; 0111: key = {7{current_state[1]}}; 1000: key = {7{current_state[2]}}; 1001: key = {7{current_state[2]}}; 1010: key = {7{current_state[2]}}; 1011: key = {7{current_state[2]}}; 1100: key = {7{current_state[3]}}; 1101: key = {7{current_state[3]}}; 1110: key = {7{current_state[3]}}; 1111: key = {7{current_state[3]}}; default: key = 8’b0; endcase

for(int i = 0; i < 8; i++) begin if(in[i] == 1’b1) decoded[i] = ~key[i]; else decoded[i] = key[i]; endendendmodule

FSM 3This design shows how typedef enum, union, unique case, and always_ff are used an arbiterdesign.

Example 4-5. SystemVerilog FSM 3

/*------------------------------------------------------------------------- Copyright (c) 2006 Mentor Graphics Corporation. All rights reserved.-- The following information has been generated by Mentor Graphics-- and may be freely distributed and modified.---- Design Module: arbiter---- Purpose : This design shows how typedef enum can be coded using SV and-- how mixed constructs between Verilog-2001 and SV are used-- within the same design

Page 161: PrecisionRTL Style

SystemVerilog Language FeaturesExample Designs

Precision Synthesis Style Guide, 2011a Update2 161November 2011

---- The following new constructs in SV are used:-- - union, typedef enum, unique case, always_ff------ Version: 1.1-- Precision: 2006a-- Date: June 15 2007-----------------------------------------------------------------------*/

module arbiter (input clock, reset, input logic req_0, req_1, output logic gnt_0, gnt_1);

//-------------Internal Constants--------------------------

localparam int SIZE = 3;typedef enum logic [SIZE-1:0] {IDLE = 3’b001, GNT0 = 3’b010, GNT1 = 3’b100}STATE_T;STATE_T state,next_state;

//----------Code startes Here------------------------

always_comb // @ (state or req_0 or req_1) --> senslist not required.begin : FSM_COMBO //next_state = 3’b000; --> illegal syntax ! unique case(state) IDLE : if (req_0 == 1’b1) begin next_state = GNT0; end else if (req_1 == 1’b1) begin next_state= GNT1; end else begin next_state = IDLE; end GNT0 : if (req_0 == 1’b1) begin next_state = GNT0; end else begin next_state = IDLE; end GNT1 : if (req_1 == 1’b1) begin next_state = GNT1; end else begin next_state = IDLE; end default : next_state = IDLE; endcaseend

always_ff @ (posedge clock)begin : FSM_SEQ if (reset == 1’b1) begin

Page 162: PrecisionRTL Style

Precision Synthesis Style Guide, 2011a Update2162

SystemVerilog Language FeaturesExample Designs

November 2011

state <= IDLE; end else begin state <= next_state; endend

//----------Output Logic-----------------------------

always_ff @ (posedge clock)begin : OUTPUT_LOGIC if (reset == 1’b1) begin gnt_0 <= 1’b0; gnt_1 <= 1’b0; end else begin priority case(state) IDLE : begin gnt_0 <= 1’b0; gnt_1 <= 1’b0; end GNT0 : begin gnt_0 <= 1’b1; gnt_1 <= 1’b0; end GNT1 : begin gnt_0 <= 1’b0; gnt_1 <= 1’b1; end default:begin gnt_0 <= 1’b0; gnt_1 <= 1’b0; end endcase endend // End Of Block OUTPUT_LOGICendmodule // End of Module arbiter

Page 163: PrecisionRTL Style

SystemVerilog Language FeaturesExample Designs

Precision Synthesis Style Guide, 2011a Update2 163November 2011

FSM ReencodedThis example uses the classic traffic light control design to illustrate const, enum, unique case,always_ff, always_comb elements, and FSM state encoding override by an applied synthesispragma.

Example 4-6. SystemVerilog FSM Reencoded

/*------------------------------------------------------------------------- Copyright (c) 2006 Mentor Graphics Corporation. All rights reserved.-- The following information has been generated by Mentor Graphics-- and may be freely distributed and modified.---- Design Module : trafficLight---- Purpose : This design shows how typedef enum can be coded using SV and-- how mixed constructs between Verilog-2001 and SV are used-- within the same design---- The following new constructs in SV are used:-- - const, enum, unique case, always_ff, always_comb------ Version: 1.0-- Precision: 2005c-- Date: Dec 23 2005-----------------------------------------------------------------------*/

module trafficLight ( output reg green_light, yellow_light, red_light, input sensor, input clock, resetN);

byte yellow_downcnt,green_downcnt;const int GREEN_COUNT = 8’d30;const int YELLOW_COUNT = 8’d05;enum logic[2:0] {RED = 3’b001, GREEN = 3’b011, YELLOW = 3’b100 }State, Next /* synthesis fsm_state = onehot */;

always_ff @(posedge clock, negedge resetN) if(!resetN) State <= RED; else begin State <= Next; if(State == GREEN) begin if(green_downcnt == 0) green_downcnt = GREEN_COUNT; else green_downcnt = green_downcnt - 1; end if(State == YELLOW) begin

Page 164: PrecisionRTL Style

Precision Synthesis Style Guide, 2011a Update2164

SystemVerilog Language FeaturesExample Designs

November 2011

if(yellow_downcnt == 0) yellow_downcnt = YELLOW_COUNT; else yellow_downcnt = yellow_downcnt - 1; end endalways_comb begin: set_next_state Next = State; unique case (State) RED: if(sensor) Next = GREEN; GREEN: if(green_downcnt == 0) Next = YELLOW; YELLOW: if(yellow_downcnt == 0) Next = RED; endcaseend:set_next_state

always_comb begin: set_outputs {red_light, green_light, yellow_light} = 3’b000; unique case(State) RED: red_light = 1; GREEN: green_light = 1; YELLOW: yellow_light = 1; endcaseend: set_outputsendmodule

Page 165: PrecisionRTL Style

SystemVerilog Language FeaturesExample Designs

Precision Synthesis Style Guide, 2011a Update2 165November 2011

InterfaceThis design uses the SystemVerilog interface feature to bundle and reuse I/O among differentmodules in the design. Modport is used to define port direction.

Example 4-7. SystemVerilog Interface

/*------------------------------------------------------------------------- Copyright (c) 2006 Mentor Graphics Corporation. All rights reserved.-- The following information has been generated by Mentor Graphics-- and may be freely distributed and modified.---- Design Module : top, memory---- Purpose : This design shows how the interface feature can he used to-- bundle and reuse I/O among different modules in the design.-- It also illustrates how modport is used to define port-- directions.---- The following new constructs in SV are used:-- - interface, typedef, always_comb------ Version: 1.0-- Precision: 2005c-- Date: Dec 23 2005-----------------------------------------------------------------------*/

interface address_bus; parameter p1 = 7; wire [p1:0] read_address; wire [p1:0] write_address; modport address_port_in (input read_address, input write_address);endinterface

interface data_bus; parameter p2 = 7; wire [p2:0] data_in; wire [p2:0] data_out; modport data_port (input data_in, output data_out);endinterface

interface control_bus; wire reset; wire clk; wire wren; wire ren;

modport memory_control (input reset, input clk, input wren, input ren);endinterface

//-----------------------------------------------------

module memory (address_bus.address_port_in addr, control_bus.memory_control ctrl, data_bus.data_port data);parameter p1 =7;

Page 166: PrecisionRTL Style

Precision Synthesis Style Guide, 2011a Update2166

SystemVerilog Language FeaturesExample Designs

November 2011

parameter p2 =7;

typedef logic [7:0] BYTE;BYTE memory[(2*p1+1):0][(2*p1+1):0];BYTE latch;

assign data.data_out = latch;

always @ (posedge ctrl.clk)begin if(ctrl.reset) begin for(int i = (2*p1+1); i >= 0; i--) begin for(int j = (2*p1+1); j >= 0; j--) begin memory[i][j] = ‘0; end end latch = ‘0; end else begin if(ctrl.ren) begin latch = memory[addr.read_address[3:0]][addr.read_address[7:4]]; end if(ctrl.wren) begin memory[addr.write_address[3:0]] [addr.write_address[7:4]] = data.data_in; end endendendmodule

//-----------------------------------------------------

module top (clk, reset, wren, ren, raddr, waddr, wdata, rdata);parameter p1 =7;parameter p2 =7;

input clk;input reset;input wren;input ren;input [p1:0] raddr;input [p1:0] waddr;input [p2:0] wdata;output [p2:0] rdata;logic [p2:0] rdata;

// Instantiate interfacesaddress_bus #(.p1(p1)) addr();data_bus #(.p2(p2)) data();control_bus ctrl();

// Instantiate memory module

Page 167: PrecisionRTL Style

SystemVerilog Language FeaturesExample Designs

Precision Synthesis Style Guide, 2011a Update2 167November 2011

memory #(.p1(p1), .p2(p2)) mem_i (.*);

assign ctrl.clk = clk;assign ctrl.reset = reset;assign ctrl.wren = wren;assign ctrl.ren = ren;assign addr.read_address = raddr;assign addr.write_address = waddr;assign data.data_in = wdata;

always_combbegin rdata = data.data_out;endendmodule

Page 168: PrecisionRTL Style

Precision Synthesis Style Guide, 2011a Update2168

SystemVerilog Language FeaturesExample Designs

November 2011

Page 169: PrecisionRTL Style

Precision Synthesis Style Guide, 2011a Update2 169November 2011

Chapter 5Inferring Arithmetic and Relational

Operators

Arithmetic and relational logic, commonly known as data path logic, has traditionally beendifficult to synthesize with logic synthesis software. This is especially true for FPGAs, whereeach target technology has a different way to optimally utilize resources. Modgen provides anautomatic mechanism to overload data path operators, such as "+", "-" and "\" technology-specific implementations.

Common GuidelinesThe following lists shows some of the guidelines for when using arithmetic and relationaloperators:

• Integer type values : Synthesis tools can handle up to 32-bit integers within the range of-2147483648 to 2147483647. During compilation, the integer signals are converted to amulti-bit representation. If the integer range only contains positive values, then aunsigned representation will be used. If the range includes negative numbers, PrecisionRTL Synthesis will use two’s-complement representation of the integer values.

• Floating Point type values : Precision RTL Synthesis does not currently supportsynthesis of floating point objects. Floating-point types and objects can however be usedin constant expression

VHDL/Verilog DifferencesThe following table shows the operator symbol differences between VHDL and Verilog:

Table 5-1. VHDL and Verilog Operator Differences

Arithmetic Operators Relational Operators

Operation VHDL Verilog Operation VHDL Verilog

Addition + + Equality = ==

Subtraction - - Inequality /= !=

Multiplication * * Lass Than < <

Division / / Less Than orEqual To

<= <=

Exponential ** N/A Greater Than > >

Page 170: PrecisionRTL Style

Precision Synthesis Style Guide, 2011a Update2170

Inferring Arithmetic and Relational OperatorsOptimization Issues

November 2011

Optimization IssuesThe " + ", " - ", " * ", and "abs" (in VHDL) operators work on integers (and on arrays; with theexemplar package). If you use overloaded operators to calculate compile time constants, thesynthesis tools will not generate any logic for them. If you are not working with compile timeconstant operands, arithmetic logic is generated for arithmetic operators. The pre-defined “+”on integers generates an adder. The number of bits of the adder depends on the size of theoperands. If you use integers, a 32 bit (signed) adder is generated. If you use ranged integers, thesize of the adder is defined so that the entire range can be represented in bits. For example, if thetwo numbers have a range of 0 to 255, then an 8 bit (unsigned) adder is generated.

If one of the operands is a constant, initially a full-sized adder is still generated but logicminimization eliminates much of the logic inside the adder, since half of the inputs of the adderare constant. The pre-defined " - " on integers generates a subtractor. Same remarks apply aswith the " + " operator.

The pre-defined " * " multiplication operator on integers generates a multiplier. Fullmultiplication is supported when a module generator is used. The pre-defined " / " divisionoperator on integers generates a divider. Only division by a power of two is supported. In thiscase, there is no logic generated, only shifting of the non-constant operand. With modulegeneration you could define your own technology-specific divider. The predefined " ** "exponentiation in VHDL is only supported if both operands are constant. " = ", " /= " or " != "," < ", " > ", " <= ", and " >= " generate comparators with the appropriate functionality.Operations on integers are done in two’s complement implementation if the integer rangeextends below 0. If the integer range is only positive, an unsigned implementation is used.There are a number of other ways to generate arithmetic logic.

Resource Sharing and Common SubexpressionElimination

Precision RTL Synthesis automatically does common sub-expression elimination. For thefollowing example, only one adder (a+b) is created. The adder is used for both the if

Modulus mod % Greater Than orEqual To

>= >=

Remainder rem N/A

Absolute Value abs N/A

Table 5-1. VHDL and Verilog Operator Differences (cont.)

Arithmetic Operators Relational Operators

Operation VHDL Verilog Operation VHDL Verilog

Page 171: PrecisionRTL Style

Inferring Arithmetic and Relational OperatorsOptimization Issues

Precision Synthesis Style Guide, 2011a Update2 171November 2011

conditions. For bigger expressions you need to use parentheses properly to direct the tool toperform for CSE.

Reducing Counter LogicApplications may involve a counter that counts up to an input signal value, and when that valueis reached, some actions are needed and the counter is reset to 0.

In this example Precision RTL Synthesis builds an incrementer and a full-size comparator thatcompares the incoming signal with the counter value. It is usually better to preset the counter tothe input_signal and count down, until zero is reached.

Now, one decrementer is needed plus a comparison to a constant (0). Since comparisons toconstants are a lot cheaper to implement, this new behavior is much easier to synthesize, andresults in a smaller circuit.

...reg a, b, c, d ;

always @ (a or b)begin

if ( a+b == c ) //This adder will be shared...

else if ( a+b == d) // with this one....

else...

end ;...

...begin

if (count == input_signal)...count = 0 ;

elsecount = count + 1 ;

end ;...

...begin

if (count == 0)...count = input_signal ;

elsecount = count - 1 ;

end ;...

Page 172: PrecisionRTL Style

Precision Synthesis Style Guide, 2011a Update2172

Inferring Arithmetic and Relational OperatorsAttributes That Affect Operators

November 2011

Even better results can be obtained with the use of hard macros and soft macros of the targettechnology, as well as the use of hierarchy in the design. The following two sections explain thisin more detail.

Attributes That Affect OperatorsThe following attributes affect how operators are implemented:

• dedicated_mult : Specifies how a multiplier operator should be mapped to resourcewithin the FPGA

Arithmetic ExamplesThe following table shows the VHDL and Verilog examples described in this section. The codefiles are available in the Precision Synthesis software tree in the following directory:

<precision_install_dir>/shared/examples/style_guide_hdl/Arithmetic:

Table 5-2. Arithmetic Examples

Example Description

Up Counter Counter that counts up on each positive clock edge, and rolls over tozero when it reaches 256.

Up Counter withEnable

Counter that has an enable signal, that stops the counting when theenable signal is low. The counter counts up on each positive clockedge, and rolls over to zero when it reaches 16.

Up Counter withEnable and Load

Counter that has an enable signal that stops the counting when theenable signal is low, and a load that will load the value in input ’a’when the load is high.

Up Counter withEnable, Load, andCout

Counter that has an active high enable signal, an active high load thatloads the value from ‘a’, and a cout bit that becomes high when thecounter is zero.

Up Counter withAsynchronous Loadand Reset

Counter that has an asynchronous load and reset. The reset resets thecount to zero and the load loads the value in input ’a’ into the count.

Down Counter Counter that counts down to zero, then rolls over to 256. It hassynchronous load and reset signals.

Bidirectional Counter Counter that can count either up or down, as determined by the inputup_down.

BCD Counter Counter that counts in binary coded decimal. In this case, the counteronly counts to 9, then rolls over to 0. There are synchronous load andreset signals, and an enable signal.

Page 173: PrecisionRTL Style

Inferring Arithmetic and Relational OperatorsArithmetic Examples

Precision Synthesis Style Guide, 2011a Update2 173November 2011

Adder with Carry-In Example of a carry-in adder. The adder adds the two inputs, ’a’ and’b’ to the ’carry-in’ bit, and outputs the sum.

Adder / Subtractor Example of an adder/subtractor that adds the inputs a and b, subtractsthe input c from d, increments e by one, and decrements f by one.

Arithmetic Logic Unit Example of an ALU that performs (0) addition (with carry-in), (1)subtraction, (2) and, (3) or, (4) xor, (5) not, (6) nand, (7) nor, (8) xnor,(9) greater than, (10) less than, (11) greater than or equal to, (12) lessthan or equal to, (13) equality, (14) shift left, and (15) shift right,according to the input sel.

Divide By N Example of a divide by n clock divider. It takes an input clock edge,and outputs a high bit every n clock edges, where n is 2^width. Theoutput signal for the divided clock is the divide signal.

Pipelined Multiplier Example that shows a pipelined multiplier, implemented using a forloop.

Table 5-2. Arithmetic Examples

Example Description

Page 174: PrecisionRTL Style

Precision Synthesis Style Guide, 2011a Update2174

Inferring Arithmetic and Relational OperatorsUp Counter

November 2011

Up CounterCounter that counts up on each positive clock edge, and rolls over to zero when it reaches 256.

VHDL Verilog

LIBRARY ieee;USE ieee.std_logic_1164.ALL;USE ieee.numeric_std.ALL;

ENTITY counter_up IS PORT(reset, load : IN STD_LOGIC; clk : IN STD_LOGIC; a : IN UNSIGNED(7 DOWNTO 0); y : OUT UNSIGNED(7 DOWNTO 0) );END ENTITY;

ARCHITECTURE rtl OF counter_up IS SIGNAL cnt : UNSIGNED(7 DOWNTO 0); constant up : STD_LOGIC := ‘1’;BEGIN PROCESS (clk) BEGIN IF (clk’EVENT AND clk = ‘1’) THEN IF (reset = ‘1’) THEN cnt <= “00000000”; ELSIF (load = ‘1’) THEN cnt <= a; ELSIF (up = ‘1’) THEN cnt <= cnt + 1; END IF; END IF; END PROCESS;

y <= cnt;

END ARCHITECTURE;

module counter_up (a, clk, reset, load, y); parameter num_range = 256; parameter up = 1;

input [7:0] a; input clk, reset, load; output [7:0] y;

reg [7:0] cnt;

always @(posedge clk) if (reset) cnt <= 0; else if (load) cnt <= a; else if (up) cnt <= cnt + 1; assign y = cnt;endmodule

Page 175: PrecisionRTL Style

Inferring Arithmetic and Relational OperatorsUp Counter with Enable

Precision Synthesis Style Guide, 2011a Update2 175November 2011

Up Counter with EnableCounter that has an enable signal, that stops the counting when the enable signal is low. Thecounter counts up on each positive clock edge, and rolls over to zero when it reaches 16.

VHDL Verilog

LIBRARY ieee;USE ieee.std_logic_1164.ALL;USE ieee.numeric_std.ALL;

ENTITY counter_up_en IS GENERIC(width: INTEGER:=4); PORT(clk, en, reset : IN STD_LOGIC; count : OUT UNSIGNED(width-1 DOWNTO 0) );END ENTITY ;

ARCHITECTURE rtl OF counter_up_en ISSIGNAL count_temp:UNSIGNED(width-1 DOWNTO 0);BEGIN count <= count_temp; PROCESS (clk) BEGIN IF (clk’EVENT AND clk=’1’) THEN IF (reset = ‘1’) THEN count_temp <= (OTHERS=>’0’); ELSIF (en = ‘1’) THEN

count_temp <= count_temp + 1; END IF; END IF; END PROCESS;END ARCHITECTURE;

module counter_up_en (clk, en,count, reset);

parameter width = 4; input clk, en, reset; output [width - 1:0] count;

reg [width - 1:0] count;

always @(posedge clk) if (reset) count = 0; else if (en) count = count + 1;endmodule

Page 176: PrecisionRTL Style

Precision Synthesis Style Guide, 2011a Update2176

Inferring Arithmetic and Relational OperatorsUp Counter with Enable and Load

November 2011

Up Counter with Enable and LoadCounter that has an enable signal that stops the counting when the enable signal is low, and aload that will load the value in input ’a’ when the load is high.

The load has priority over the enable. The counter counts up on each positive clock edge, androlls over to zero when it reaches 16.

VHDL Verilog

LIBRARY ieee;USE ieee.std_logic_1164.ALL;USE ieee.numeric_std.ALL;

ENTITY counter_up_en_ld IS GENERIC(width: INTEGER:=4); PORT(clk, en : IN STD_LOGIC; load, reset : IN STD_LOGIC; a : IN UNSIGNED(width-1 DOWNTO 0); count : OUT UNSIGNED (width-1 DOWNTO 0) );END ENTITY ;

ARCHITECTURE rtl OF counter_up_en_ld ISSIGNAL count_temp:UNSIGNED (width-1 DOWNTO 0);BEGIN PROCESS (clk) BEGIN IF (clk’EVENT AND clk=’1’) THEN IF (reset = ‘1’) THEN count_temp <= (OTHERS=>’0’); ELSIF (load = ‘1’) THEN count_temp <= a; ELSIF (en = ‘1’) THEN count_temp <= count_temp + 1; END IF; END IF; END PROCESS;count <= count_temp;END ARCHITECTURE;

module counter_up_en_load (clk, en, a,

load,count,reset);

parameter width = 4; input clk, en, load, reset; input [width - 1:0] a; output [width - 1:0] count;

reg [width - 1:0] count;

always @(posedge clk) if (reset) count <= 0; else if (load) count <= a; else if (en) count <= count + 1;endmodule

Page 177: PrecisionRTL Style

Inferring Arithmetic and Relational OperatorsUp Counter with Enable, Load, and Cout

Precision Synthesis Style Guide, 2011a Update2 177November 2011

Up Counter with Enable, Load, and CoutCounter that has an active high enable signal, an active high load that loads the value from ‘a’,and a cout bit that becomes high when the counter is zero.

The load has priority over the enable. The counter counts up on each positive clock edge, androlls over to zero at 16.

VHDL Verilog

LIBRARY ieee;USE ieee.std_logic_1164.ALL;USE ieee.numeric_std.ALL;

ENTITY counter_up_en_load_cout IS GENERIC(width: INTEGER:=4); PORT(clk, en : IN STD_LOGIC; reset, load: IN STD_LOGIC; a : IN UNSIGNED (width - 1 DOWNTO 0); cout : OUT STD_LOGIC; count : OUT UNSIGNED (width-1 DOWNTO 0) );END ENTITY;

ARCHITECTURE rtl OF counter_up_en_load_cout ISSIGNAL count_temp : UNSIGNED (width-1 DOWNTO 0);CONSTANT max : UNSIGNED (width-1 DOWNTO 0

) := (OTHERS=>’1’);BEGIN count <= count_temp; PROCESS (clk) BEGIN IF (clk’EVENT AND clk=’1’) THEN IF (reset = ‘1’) THEN count_temp <= (OTHERS=>’0’); cout <= ‘0’; ELSIF (load = ‘1’) THEN count_temp <= a; ELSIF (en = ‘1’) THEN count_temp <= count_temp + 1; END IF; IF (count_temp = “0000”) THEN cout <= ‘1’; ELSE cout <=’0’; END IF; END IF; END PROCESS;END ARCHITECTURE;

module counter_up_en_load_cout (clk, en, load, a, cout,

count,reset);

parameter width = 4; input clk, en, load, reset; input [width - 1:0] a; output cout; output [width - 1:0] count;

reg [width - 1:0] count; reg cout;

always @(posedge clk) begin if (reset) count <= 0; else if (load) count <= a; else if (en) count <= count + 1; if (count == 0) cout <= 1; else cout <= 0; endendmodule

Page 178: PrecisionRTL Style

Precision Synthesis Style Guide, 2011a Update2178

Inferring Arithmetic and Relational OperatorsUp Counter with Asynchronous Load and Reset

November 2011

Up Counter with Asynchronous Load and ResetCounter that has an asynchronous load and reset. The reset resets the count to zero and the loadloads the value in input ’a’ into the count.

These both operate independent of the clock edge, and therefore must be included in thesensitivity list The counter counts up to 256, then rolls over to zero.

VHDL Verilog

LIBRARY IEEE;USE IEEE.STD_LOGIC_1164.ALL;USE IEEE.NUMERIC_STD.ALL;

ENTITY counter_up_asynch ISPORT ( a: IN UNSIGNED (7 DOWNTO 0);

clk, reset, load: IN STD_LOGIC; y: OUT UNSIGNED (7 DOWNTO 0));END ENTITY;

ARCHITECTURE rtl OF counter_up_asynchIS

SIGNAL count : UNSIGNED(7 DOWNTO 0);BEGIN PROCESS (clk, reset, load) BEGIN IF (reset = ‘1’) THEN count <= “00000000”; ELSIF (load = ‘1’) THEN count <= a; ELSIF (clk’EVENT AND clk = ‘1’)

THEN count <= count + 1; END IF;

y <= count;

END PROCESS;

END ARCHITECTURE;

module counter_up_asynch (a, clk, reset, load, y); input [7:0] a; input clk, reset, load; output [7:0] y;

reg [7:0] cnt;

always @(posedge clk or posedge reset or posedge load) if (reset) cnt <= 0; else if (load) cnt <= a; else cnt <= cnt + 1;

assign y = cnt;

endmodule

Page 179: PrecisionRTL Style

Inferring Arithmetic and Relational OperatorsDown Counter

Precision Synthesis Style Guide, 2011a Update2 179November 2011

Down CounterCounter that counts down to zero, then rolls over to 256. It has synchronous load and resetsignals.

VHDL Verilog

LIBRARY ieee;USE ieee.std_logic_1164.ALL;USE ieee.numeric_std.ALL;

ENTITY counter_down IS PORT(reset, load : IN STD_LOGIC; clk : IN STD_LOGIC; a : IN UNSIGNED(7 DOWNTO 0); y : OUT UNSIGNED(7 DOWNTO 0) );END ENTITY;

ARCHITECTURE rtl OF counter_down IS SIGNAL cnt : UNSIGNED (7 DOWNTO 0); CONSTANT down : STD_LOGIC := ‘1’;BEGIN PROCESS (clk) BEGIN IF (clk’EVENT AND clk = ‘1’) THEN IF (reset = ‘1’) THEN cnt <= “00000000”; ELSIF (load = ‘1’) THEN cnt <= a; ELSIF (down = ‘1’) THEN cnt <= cnt - 1; END IF; END IF; END PROCESS;

y <= cnt;

END ARCHITECTURE;

module counter_down (a, clk, reset, load, y); parameter num_range = 256; parameter down = 1;

input [7:0] a; input clk, reset, load; output [7:0] y;

reg [7:0] cnt;

always @(posedge clk) if (reset) cnt <= 0; else if (load) cnt <= a; else if (down) cnt <= cnt - 1;

assign y = cnt;endmodule

Page 180: PrecisionRTL Style

Precision Synthesis Style Guide, 2011a Update2180

Inferring Arithmetic and Relational OperatorsBidirectional Counter

November 2011

Bidirectional CounterCounter that can count either up or down, as determined by the input up_down.

When up_down is high it counts up, when it is low it counts down. There are also asynchronousload and reset signals. The maximum count value is 256.

VHDL Verilog

LIBRARY ieee;USE ieee.std_logic_1164.ALL;USE ieee.numeric_std.ALL;

ENTITY count_updn IS PORT(reset, load : IN STD_LOGIC; updn, clk : IN STD_LOGIC; a : IN UNSIGNED(7 DOWNTO 0); y : OUT UNSIGNED(7 DOWNTO 0) );END count_updn;

ARCHITECTURE rtl OF count_updn IS SIGNAL cnt : UNSIGNED (7 DOWNTO 0);BEGIN PROCESS (clk) BEGIN IF (clk’EVENT AND clk = ‘1’) THEN IF (reset = ‘1’) THEN cnt <= “00000000”; ELSIF (load = ‘1’) THEN cnt <= a; ELSIF (updn = ‘1’) THEN cnt <= cnt + 1; ELSE cnt <= cnt - 1; END IF; END IF; END PROCESS;

y <= cnt;

END ARCHITECTURE;

module bidir_counter (a, clk, reset,load, up_down,

y);

input [7:0] a;input clk, reset, load, up_down;

output [7:0] y;

reg [7:0] cnt;

always @(posedge clk) if (reset) cnt <= 0; else if (load) cnt <= a; else if (up_down) cnt <= cnt + 1; else cnt <= cnt - 1;

assign y = cnt;endmodule

Page 181: PrecisionRTL Style

Inferring Arithmetic and Relational OperatorsBCD Counter

Precision Synthesis Style Guide, 2011a Update2 181November 2011

BCD CounterCounter that counts in binary coded decimal. In this case, the counter only counts to 9, then rollsover to 0. There are synchronous load and reset signals, and an enable signal.

VHDL Verilog

LIBRARY ieee ;USE ieee.STD_LOGIC_1164.ALL;USE ieee.numeric_std.ALL;

ENTITY counter_bcd IS PORT(en, reset : IN STD_LOGIC; clk, load : IN STD_LOGIC; a : IN UNSIGNED(3 DOWNTO 0); count : OUT UNSIGNED (3 DOWNTO 0); cout : OUT STD_LOGIC);END ENTITY ;

ARCHITECTURE rtl OF counter_bcd ISSIGNAL count_temp : UNSIGNED (3 DOWNTO 0);BEGIN PROCESS (clk) BEGIN IF (clk’EVENT AND clk=’1’) THEN IF (reset = ‘1’) THEN count_temp <= “0000”; ELSIF (load = ‘1’) THEN count_temp <= a; ELSIF (count_temp = 9) THEN count_temp <= “0000”; cout <= ‘1’; ELSIF (en = ‘1’) THEN count_temp <= count_temp+1; cout <= ‘0’; END IF; END IF; END PROCESS; count <= count_temp;END ARCHITECTURE;

module counter_bcd (clk, en, reset, load, a, count, cout); input clk, en, reset, load; input [3:0] a; output cout; output [3:0] count;

reg cout; reg [3:0] count;

always @(posedge clk) if (reset) count <= 0; else if (load) count <= a; else if (count == 9) begin count <= 0; cout <= 1; end else if (en) begin count <= count + 1; cout <= 0; endendmodule

Page 182: PrecisionRTL Style

Precision Synthesis Style Guide, 2011a Update2182

Inferring Arithmetic and Relational OperatorsAdder with Carry-In

November 2011

Adder with Carry-InExample of a carry-in adder. The adder adds the two inputs, ’a’ and ’b’ to the ’carry-in’ bit, andoutputs the sum.

VHDL Verilog

LIBRARY ieee;USE ieee.std_logic_1164.ALL;USE ieee.numeric_std.ALL;

ENTITY adder_cin IS GENERIC (width : INTEGER := 4); PORT (a, b : IN UNSIGNED (width-1 DOWNTO 0); cin : IN STD_LOGIC; sum: OUT UNSIGNED

(width DOWNTO 0));END ENTITY;

ARCHITECTURE rtl OF adder_cin ISBEGINPROCESS (a, b, cin)BEGIN IF (cin = ‘1’) THEN sum <= (‘0’ & a) + (‘0’ & b) + 1; ELSE sum <= (‘0’ & a) + (‘0’ & b); END IF;END PROCESS;END ARCHITECTURE;

module adder_cin (a, b, cin, sum); parameter width = 4; input [width - 1:0] a; input [width - 1:0] b; input cin; output [width:0] sum;

reg [width:0] sum;

always @(a or b or cin) if (cin) sum = {1’b0,a} + {1’b0,b} + 1; else sum = {1’b0,a} + {1’b0,b};endmodule

Page 183: PrecisionRTL Style

Inferring Arithmetic and Relational OperatorsAdder / Subtractor

Precision Synthesis Style Guide, 2011a Update2 183November 2011

Adder / SubtractorExample of an adder/subtractor that adds the inputs a and b, subtracts the input c from d,increments e by one, and decrements f by one.

VHDL Verilog

LIBRARY ieee ;USE ieee.std_logic_1164.ALL;USE ieee.numeric_std.ALL;

ENTITY addsub IS PORT (a, b, c, d, e, f : IN UNSIGNED (3 DOWNTO 0); add, sub, inc, dec : OUT UNSIGNED (3 DOWNTO 0));

END ENTITY;

ARCHITECTURE rtl OF addsub ISBEGIN add <= a + b; sub <= c - d; inc <= e + 1; dec <= f - 1;END ARCHITECTURE;

module addsub (a, b, c, d, e, f, add, sub, inc, dec);

input [3:0] a, b, c, d, e, f;output [3:0] add, sub, inc, dec;

assign add = a + b; assign sub = c - d; assign inc = e + 1; assign dec = f - 1;

endmodule

Page 184: PrecisionRTL Style

Precision Synthesis Style Guide, 2011a Update2184

Inferring Arithmetic and Relational OperatorsArithmetic Logic Unit

November 2011

Arithmetic Logic UnitExample of an ALU that performs (0) addition (with carry-in), (1) subtraction, (2) and, (3) or,(4) xor, (5) not, (6) nand, (7) nor, (8) xnor, (9) greater than, (10) less than, (11) greater than orequal to, (12) less than or equal to, (13) equality, (14) shift left, and (15) shift right, according tothe input sel.

VHDL

LIBRARY IEEE;USE IEEE.STD_LOGIC_1164.ALL;USE IEEE.NUMERIC_STD.ALL;

ENTITY ALU ISPORT ( cin : IN STD_LOGIC; sel : IN UNSIGNED (3 DOWNTO 0); a, b : IN UNSIGNED (7 DOWNTO 0); cout: OUT STD_LOGIC; y: OUT UNSIGNED (7 DOWNTO 0) );END ENTITY;

ARCHITECTURE rtl OF ALU IS SIGNAL temp: UNSIGNED (8 DOWNTO 0); BEGIN PROCESS (sel, a, b, cin) BEGIN

cout <= ‘0’;y <= “00000000”;CASE (sel) ISWHEN “0000” =>

temp <= (‘0’ & a) + (‘0’ & b) + (‘0’ & cin);y <= temp (7 DOWNTO 0);cout <= temp (8);

WHEN “0001” => y <= a - b;

IF (a < b) THEN cout <= ‘1’; ELSE cout <= ‘0’; END IF;

WHEN “0010” => y <= a AND b;WHEN “0011” => y <= a OR b;WHEN “0100” => y <= a XOR b;WHEN “0101” => y <= NOT a;WHEN “0110” => y <= a nor b;WHEN “0111” => y <= a NAND b;WHEN “1000” => y <= a XNOR b;WHEN “1001” =>

IF (a > b) THEN cout <= ‘1’; ELSE cout <= ‘0’; END IF;

WHEN “1010” => IF (a < b) THEN cout <= ‘1’; ELSE cout <= ‘0’; END IF;

WHEN “1011” =>

Page 185: PrecisionRTL Style

Inferring Arithmetic and Relational OperatorsArithmetic Logic Unit

Precision Synthesis Style Guide, 2011a Update2 185November 2011

IF (a >= b) THEN cout <= ‘1’; ELSE cout <= ‘0’; END IF;

WHEN “1100” => IF (a <= b) THEN cout <= ‘1’; ELSE cout <= ‘0’; END IF;

WHEN “1101” => IF (a = b) THEN cout <= ‘1’; ELSE cout <= ‘0’; END IF;

WHEN “1110” => y <= shift_left (a, 1);WHEN “1111” => y <= shift_right (b, 1);WHEN OTHERS => y <= “XXXXXXXX”;END CASE;

END PROCESS;END ARCHITECTURE;

Page 186: PrecisionRTL Style

Precision Synthesis Style Guide, 2011a Update2186

Inferring Arithmetic and Relational OperatorsArithmetic Logic Unit

November 2011

Verilog

module ALU (sel, a, b, cin, cout, y);input cin;input [7:0] sel, a, b;output cout;output [7:0] y;reg cout;reg [7:0] y;reg [8:0] temp; always @ (sel or a or b or cin) begin cout = 0; y = 8’b00000000; case (sel) 4’b0000: begin temp = a + b + cin; y = temp [7:0]; cout = temp [8]; end 4’b0001: begin y = a - b; cout = (a > b) ? 1 : 0; end 4’b0010: y = a & b; 4’b0011: y = a | b; 4’b0100: y = a ^ b; 4’b0101: y = !a; 4’b0110: y = !(a | b); 4’b0111: y = !(a & b); 4’b1000: y = a ~^ b; 4’b1001: cout = (a > b) ? 1 : 0; 4’b1010: cout = (a < b) ? 1 : 0; 4’b1011: cout = (a >= b) ? 1 : 0; 4’b1100: cout = (a <= b) ? 1 : 0; 4’b1101: cout = (a == b) ? 1 : 0; 4’b1110: y = a << 1; 4’b1111: y = b >> 1; endcase endendmodule

Page 187: PrecisionRTL Style

Inferring Arithmetic and Relational OperatorsDivide By N

Precision Synthesis Style Guide, 2011a Update2 187November 2011

Divide By NExample of a divide by n clock divider. It takes an input clock edge, and outputs a high bit everyn clock edges, where n is 2^width. The output signal for the divided clock is the divide signal.

VHDL Verilog

LIBRARY IEEE;USE IEEE.std_logic_1164.ALL;USE IEEE.numeric_std.ALL;

ENTITY divide_by_n IS generic (width : NATURAL := 8); PORT (data_in : IN UNSIGNED (width-1 DOWNTO 0); load : IN STD_LOGIC; clk : IN STD_LOGIC; reset : IN STD_LOGIC; divide : OUT STD_LOGIC);END ENTITY;

ARCHITECTURE rtl OF divide_by_n IS SIGNAL cnt_reg : UNSIGNED (width-1

DOWNTO 0); constant max_cnt : UNSIGNED (width-

1 DOWNTO 0) := (OTHERS=>’1’); BEGIN cnt_it : PROCESS (clk, reset) BEGIN IF (reset = ‘1’) THEN cnt_reg <= (OTHERS =>

‘0’); ELSIF (clk = ‘1’ AND clk’EVENT) THEN IF (load = ‘1’) THEN cnt_reg <= data_in; ELSE cnt_reg <=

cnt_reg+”01”; END IF; END IF; END PROCESS; divide <= ‘1’ WHEN cnt_reg =

max_cnt ELSE ‘0’;END ARCHITECTURE ;

module divide_by_n (data_in, load,clk, reset, divide);

parameter width = 8;

input [width-1:0] data_in; input load, clk, reset; output divide;

wire divide; wire [width-1:0] max_cnt = (1 << width) -1;

reg [width-1:0] cnt_reg;

always @(posedge clk or posedge reset) if (reset) cnt_reg <= 0; else if (load) cnt_reg <= data_in; else cnt_reg <= cnt_reg + 1;

assign divide = (cnt_reg==max_cnt) ? 1 : 0;endmodule

Page 188: PrecisionRTL Style

Precision Synthesis Style Guide, 2011a Update2188

Inferring Arithmetic and Relational OperatorsPipelined Multiplier

November 2011

Pipelined MultiplierExample that shows a pipelined multiplier, implemented using a for loop.

VHDL Verilog

LIBRARY ieee ;USE ieee.std_logic_1164.ALL;USE ieee.numeric_std.ALL;

ENTITY pipelined_mult IS generic (size : INTEGER := 16; level : INTEGER := 4); PORT (a : IN UNSIGNED (size-1 DOWNTO 0); b : IN UNSIGNED (size-1 DOWNTO 0); clk : IN STD_LOGIC; y : OUT UNSIGNED (2*size-1 DOWNTO 0));END ENTITY;

ARCHITECTURE rtl OF pipelined_mult ISTYPE levels_of_registers IS array (level-1 DOWNTO 0) OF UNSIGNED (2*size-1 DOWNTO 0);SIGNAL a_int,b_int : UNSIGNED

(size-1 DOWNTO 0);SIGNAL pdt_int : levels_of_registers;

BEGIN y <= UNSIGNED (pdt_int (level-1)); PROCESS(clk) BEGIN IF (clk’EVENT AND clk = ‘1’) THEN a_int <= UNSIGNED (a); b_int <= UNSIGNED (b); pdt_int(0) <= a_int * b_int; FOR i IN 1 TO level-1 LOOP

pdt_int (i) <= pdt_int (i-1); END LOOP; END IF; END PROCESS;END ARCHITECTURE;

module pipelined_multiplier (a, b, clk, y); parameter size = 16, level = 4;

input [size-1 : 0] a; input [size-1 : 0] b; input clk;

output [2*size-1 : 0] y;

reg [size-1 : 0] a_int, b_int; reg [2*size-1 : 0] pdt_int [level-1 : 0];

integer i;

assign y = pdt_int [level-1];

always @ (posedge clk) begin a_int <= a; b_int <= b; pdt_int[0] <= a_int * b_int; for (i = 1; i < level; i = i + 1) pdt_int [i] <= pdt_int [i-1]; endendmodule

Page 189: PrecisionRTL Style

Precision Synthesis Style Guide, 2011a Update2 189November 2011

Chapter 6Boolean Logic

Boolean Logic, or combinational logic, is made up of the basic gates. This is created usingconditional statements, such as an if-then-else or case statement.

Common GuidelinesSynthesis tools implement boolean logic from boolean logic operators in the HDL design or canbe inferred.

VHDL/Verilog DifferencesThe following table shows the boolean operators for VHDL and Verilog:

Optimization IssuesThe following subsections describe some of the optimization issues that may be encounteredwhen inferring boolean logic.

Unintended Combinatorial Loops (Latches)According to the VHDL LRM, if nothing is assigned to a signal during a run through a process,the signal must retain its old value. In synthesis, If no assignment is made to a signal in acombinatoric process, combinational loops (latches) have to be generated to preserve the oldvalue.

Table 6-1. VHDL and Verilog Boolean Operators

Boolean Operator VHDL Verilog

AND and && (logical) & (bitwise)

OR or || (logical) | (bitwise)

XOR xor ^ (logical) ^ (bitwise)

NOT not ! (logical) ~ (bitwise)

NAND nand no explicit operator

NOR nor no explicit operator

XNOR xnor ~^ or ^~ (bitwise)

Page 190: PrecisionRTL Style

Precision Synthesis Style Guide, 2011a Update2190

Boolean LogicOptimization Issues

November 2011

Incomplete CASE statementNot assigning a value to a signal during an iteration through a process infers a latch. Typically,these are really “don’t care” conditions. Assigning the signal to some value will be less costly interms of area.

In this example, we see that not assigning to out_sig in the clause for state3 implies a latch. Asa general rule, every clause in a case statement should assign a value to the same outputs.

To fix this problem you can assign the out_sig signal a value before the case statement isentered, thus removing the implied latch. The resulting design is 30% smaller, and does nothave combinatoric feedback which will require latching.

It is important to understand that omitting a VHDL statement can imply extra logic!

PROCESS (curr_state,a,b);BEGIN CASE curr_state IS WHEN state1 => next_state <= state2;

out_sig <= a; WHEN state2 => next_state <= state3;

out_sig <= b; WHEN state3 => next_state <= state1;

-- No assignment to out_sig END CASE;end process

next_state

B

Aout_sig

curr_state

a

b

next_state(0)

next_state(1)

out_sig

curr_state(0)

curr_state(1)

Page 191: PrecisionRTL Style

Boolean LogicOptimization Issues

Precision Synthesis Style Guide, 2011a Update2 191November 2011

Incomplete IF statementsIF-THEN-ELSE statements can also be incomplete. For example, consider the following:

PROCESS(a,b,c,d)BEGIN IF (a = ‘1’) THEN out_sig <= x; ELSIF (b = ‘1’) THEN out_sig <= y; ENDIF;END PROCESS;

Note that a latch is required to hold the value in the case where a=b=’0’. To eliminate this latch,you could add an ELSE clause.

Incomplete Reset ConditionsIn this example, count_old must be retained when reset is 0. This causes a loop to be created.This is likely not the intended results.

PROCESS (clk, reset);BEGIN if (reset = ‘0’) then count <= 0; elsif rising_edge(clk) then count_old <= count; count <= count + 1; end if;end process;

count_old is not assigned in the reset condition. The value must be retained

PROCESS (curr_state,a,b);BEGIN out_sig <= ‘0’;

-- default CASE curr_state IS WHEN state1 => next_state <= state2; out_sig <= a; WHEN state2 => next_state <= state3; out_sig <= b; WHEN state3 => next_state <= state1; END CASE;end process;

curr_state(0)curr_state(1)

a

b

next_state(0

next_state(1)

out_sig

Page 192: PrecisionRTL Style

Precision Synthesis Style Guide, 2011a Update2192

Boolean LogicAttributes Relating to Boolean Logic

November 2011

Using Variables before they are assignedSynthesis ignores the simulation initial value assigned to temp. Synthesis only recognizeshardware resets. With this in mind, you can see that the variable “temp” on the (right-hand side)of the assignment does not have a value the first time through the loop. This occurs each time“d” changes. So the old value will be latched.

ENTITY parity is PORT (d : IN std_logic_vector(7 DOWNTO 0); y : OUT std_logic);END parity;

ARCHITECTURE comb_loop OF parity isBEGIN PROCESS (d) VARIABLE temp : std_logic := ‘0’; BEGIN FOR i IN d’RANGE LOOP temp := temp XOR d(i); -- Used Before Assigned! END LOOP; y <= temp; END PROCESS;END comb_loop;

Attributes Relating to Boolean LogicThe following attributes affect boolean logic:

• array_pin_number: This VHDL only attribute makes it easier to assign pin numbers tobuses.

• preserve_driver: added to a net to retain the driving gate through optimization. Thisattribute may prevent some optimization with the surrounding logic but it will keep thelogic and the net name. This attribute is typically used when you need to retain a signalname for additional constraints or simulation points.

• preserve_z: prevents tri-states from being mapped to MUX logic.

+1

Reset

Count_old +1

Reset

Count_old

0

1

DESIRED RESULT ACTUAL RESULT

Clock

Clock

Page 193: PrecisionRTL Style

Boolean LogicBoolean Examples

Precision Synthesis Style Guide, 2011a Update2 193November 2011

Boolean ExamplesThe following table shows the VHDL and Verilog examples described in this section. The codefiles are available in the Precision Synthesis software tree in the following directory:

<precision_install_dir>/shared/examples/style_guide_hdl/Boolean_Logic

Table 6-2. Boolean Logic Examples

Example Description

Basic Gates Example that demonstrates how to create each of the basic gates.

Tri-State Example of how to implement tri-state logic. This third state is thehigh-impedance state.

Tri-State Bus Example of a generic width tri-state bus with the width set to 4. A busis an array of bits with (multiple) three-state drivers.

Bi-Directional Bus Example of a generic width bi-directional bus set to a width of 4.

Generic WidthDecoder

Example of a generic width decoder. The width in and width out arespecified in the entity. This decoder has an input width of 2, and anoutput width of 4.

Seven SegmentDecoder

Example of a decoder that could be used with a seven segment LEDdisplay.

Priority Encoder Example of an 8-bit priority encoder.

Multiplexer Example of a generic bus width 8 to 1 multiplexer. It is implementedusing a case statement.

Parallel Mux Example of a parallel multiplexer. All inputs have equal priority in aparallel MUX.

Serial Mux Example design that creates a series of muxes, which forms priorityusing if statements.

Page 194: PrecisionRTL Style

Precision Synthesis Style Guide, 2011a Update2194

Boolean LogicBasic Gates

November 2011

Basic GatesExample that demonstrates how to create each of the basicgates.

VHDL Verilog

LIBRARY ieee;USE ieee.std_logic_1164.ALL;

ENTITY basic_gates IS PORT (a, b: IN STD_LOGIC;

y_and, y_or, y_xor, y_not, y_nand, y_nor, y_xnor: OUT STD_LOGIC);END ENTITY;

ARCHITECTURE rtl OF basic_gates ISBEGIN y_and <= a AND b; y_or <= a OR b; y_xor <= a XOR b; y_not <= NOT a; y_nand <= a NAND b; y_nor <= a NOR b; y_xnor <= a XNOR b;END ARCHITECTURE;

module basic_gates (a, b, y_and, y_or, y_xor, y_not, y_nand, y_nor, y_xnor); input a, b;

output y_and, y_or, y_xor, y_not, y_nand, y_nor, y_xnor;

assign y_and = a & b; assign y_or = a | b; assign y_xor = a ^ b; assign y_not = ~a; assign y_nand = !(a & b); assign y_nor = !(a | b); assign y_xnor = a ~^ b;

endmodule

Page 195: PrecisionRTL Style

Boolean LogicTri-State

Precision Synthesis Style Guide, 2011a Update2 195November 2011

Tri-StateExample of how to implement tri-state logic. This third stateis the high-impedance state.

In VHDL, you cannot have a BIT type variable when usingtri-states; instead, use the STD_LOGIC type. A tri-stategives a third possible state on top of the standard high andlow logic levels. This is called high-impedance, and isspecified using the letter Z.

In the conditional clause of the signal assignment, both a and en can be full expressions.Precision RTL Synthesis generates combinational logic driving the input or the enable of thetristate buffer for these expressions. However, the use of the ’z’ value in an expression isillegal.

VHDL Verilog

LIBRARY ieee;USE ieee.std_logic_1164.ALL;

ENTITY tristate IS PORT(a, en : IN STD_LOGIC; y : OUT STD_LOGIC);END ENTITY ;

ARCHITECTURE rtl OF tristate ISBEGIN y <= a WHEN (en = ‘1’) ELSE ‘Z’;END ARCHITECTURE;

module tristate (a, en, y); input a, en; output y;

assign y = en ? a : 1’bZ;

endmodule

Page 196: PrecisionRTL Style

Precision Synthesis Style Guide, 2011a Update2196

Boolean LogicTri-State Bus

November 2011

Tri-State BusExample of a generic width tri-state bus with the widthset to 4. A bus is an array of bits with (multiple) three-state drivers.

In VHDL, the type of the bus signal should bestd_logic_vector, because the BIT type does not supporttri-states. The ’Z’ character for tri-states has to be astring literal when used in a bus.

You can still introduce a data conflict with tristates byenabling more than one tristate on a net. Precision RTLSynthesis does not check for a possible bus conflict.Make sure that you can never have that possibility bycarefully generating the enable signals for the tristateconditions.

These examples show assignments to outputs. However, it is certainly possible to do theassignments to an internal wire as well.

VHDL Verilog

LIBRARY ieee;USE ieee.std_logic_1164.ALL;USE ieee.numeric_std.ALL;

ENTITY tristate_bus IS GENERIC(width : INTEGER := 4); PORT(en : IN STD_LOGIC;

a : IN UNSIGNED(width-1 DOWNTO 0);y : OUT UNSIGNED(width-1 DOWNTO 0)

);END ENTITY ;

ARCHITECTURE rtl OF tristate_bus ISBEGIN y <= a WHEN (en=’1’) ELSE

(OTHERS=>’Z’);END ARCHITECTURE;

module tristate_bus (a, en, y); parameter width = 4; input [width - 1:0] a; input en; output [width - 1:0] y;

assign y = en ? a : 4’bZ;

endmodule

Page 197: PrecisionRTL Style

Boolean LogicBi-Directional Bus

Precision Synthesis Style Guide, 2011a Update2 197November 2011

Bi-Directional BusExample of a generic width bi-directional bus set to a width of 4.

Bidirectional I/O buffers will be created if an external port is both used and assigned inside thearchitecture. If the output itself is used again internally, the port must be declared to be inout.An enable signal could also be generated from inside the architecture, instead of being aprimary input. If needed, a suitable bidirectional buffer is selected from the target technologylibrary. If there is no bidirectional buffer available, it selects a combination of a three-statebuffer and an input buffer.

Example 6-1. VHDL Bi-Directional Bus

LIBRARY ieee;USE ieee.std_logic_1164.ALL;USE ieee.numeric_std.ALL;

ENTITY bidir_bus IS GENERIC(width : INTEGER := 4); PORT( bidir : INOUT UNSIGNED(width-1 DOWNTO 0); out_enable : IN STD_LOGIC; a : IN UNSIGNED(width-1 DOWNTO 0); y : OUT UNSIGNED(width-1 DOWNTO 0) );END ENTITY ;

ARCHITECTURE rtl OF bidir_bus ISBEGIN y <= bidir; bidir <= a WHEN out_enable = ‘1’ ELSE (OTHERS => ‘Z’);END ARCHITECTURE;

Example 6-2. Verilog Bi-Directional Bus

module bidir_bus (bidir, out_enable, a, y); parameter width = 4;

input out_enable; input [width-1:0] a; output [width-1:0] y; inout [width-1:0] bidir;

wire [width-1:0] y, a;

assign y = bidir; assign bidir = out_enable ? a : 4’bz;

endmodule

Page 198: PrecisionRTL Style

Precision Synthesis Style Guide, 2011a Update2198

Boolean LogicGeneric Width Decoder

November 2011

Generic Width DecoderExample of a generic width decoder. Thewidth in and width out are specified in theentity. This decoder has an input width of 2,and an output width of 4.

VHDL Verilog

LIBRARY ieee;USE ieee.std_logic_1164.ALL;USE ieee.numeric_std.ALL;

ENTITY decoder_gen IS GENERIC(widthin : INTEGER := 2; widthout : INTEGER := 4); PORT(a : IN UNSIGNED(widthin-1 DOWNTO 0); y : OUT UNSIGNED(widthout-1 DOWNTO 0));END ENTITY;

ARCHITECTURE rtl OF decoder_gen ISBEGIN PROCESS (a) BEGIN FOR i IN 0 TO widthout - 1 LOOP IF (to_integer(a) = i) THEN y(i) <= ‘1’; ELSE y(i) <= ‘0’; END IF; END LOOP; END PROCESS;END ARCHITECTURE;

module decoder_gen (a, y); parameter widthin = 2; parameter widthout = 4; input [widthin - 1:0] a; output [widthout - 1:0] y;

reg [widthout - 1:0] y; integer i;

always @(a) for (i=0; i<=widthout-1; i=i+1) if (a == i) y[i] = 1; else y[i] = 0;endmodule

Page 199: PrecisionRTL Style

Boolean LogicI/O Buffers

Precision Synthesis Style Guide, 2011a Update2 199November 2011

I/O BuffersIO Buffers must be added to a design before it can go through place and route. Precisionprovides several options by which you can specify the IO buffers to use.

By default, Precision RTL Synthesis automatically assigns I/O buffers to the ports of you designunless you turn off the feature from the GUI pulldown menu Tools > Set Options... Input >Options > Add IO Pads. You can also disable the feature with the command setup_design -

addio=false. You can also overwrite any default buffer assignment that Precision RTLSynthesis may make by assigning the buffer_sig attribute to a port or a net. In addition, youmay also choose to instantiate the buffer component directly into the design. Either way, it isimportant to realize that if you specify buffer names in the HDL source, Precision RTLSynthesis checks the source technology library to find the buffer you are requesting. If thebuffer is not found, an error occurs.

The following list describes the available methods on inserting two-terminal IO buffers intoyour design:

• HDL Instantiation. You can directly instantiate buffers as vender cells. This approachgives you full control, which may be necessary if the buffer is complex (more than twopins). The disadvantage is that it will make the HDL design become technology specific.Consider the following code segment:

• In this example, component instantiation forces an OUTPUT_FF buffer (complex I/Ooutput/flip-flop buffer) on the bidirectional pin inoutp. Also an input bufferINPUT_BUFFER is specified to pick up the value from inp to be used internally. In thecase of component instantiation of I/O buffers, the right source technology must bespecified when you setup the design to assure that Precision RTL Synthesis takes theinstantiated I/O buffer from the right library.

• buffer_sig attribute. This attribute is attached to a port in the source VHDL. This alsomakes your HDL source code technology specific, but attributes can be over-ridden inthe synthesis tool, so it is less of a problem to re-target a design.

• Automatic IO Instantiation. During synthesize, IO buffers will be placed on externalsignals. In addition, many technologies buffer clock signals with special buffers. Thecontrol over the buffer selection is limited here, but if the results are ok, this is certainlythe easiest and most technology-independent method. This option is chosen via a check-box in the Setup Design dialog box.

module special_buffer_example (inp, clk, outp, inoutp) ;input inp, clk ;output outp ;inout inoutp ;wire intern_in, intern_out, io_control ;

OUTPUT_FF A1(.c(clk), .d(intern_out), .t(io_control),.o(inoutp));INPUT_BUFFER A2(.i(inp), .o(intern_in)) ;

endmodule

Page 200: PrecisionRTL Style

Precision Synthesis Style Guide, 2011a Update2200

Boolean LogicSeven Segment Decoder

November 2011

Seven Segment DecoderExample of adecoder that couldbe used with aseven segmentLED display.

VHDL Verilog

LIBRARY ieee;USE ieee.std_logic_1164.ALL;USE ieee.numeric_std.ALL;

ENTITY seven_seg_dec IS

PORT( a : IN UNSIGNED(3 DOWNTO 0); y : OUT UNSIGNED(6 DOWNTO 0));END ENTITY ;

ARCHITECTURE rtl OF seven_seg_dec IS BEGIN PROCESS (a) BEGIN CASE a IS WHEN “0000” => y <= “1111110”; WHEN “0001” => y <= “0100000”; WHEN “0010” => y <= “1101101”; WHEN “0011” => y <= “1111001”; WHEN “0100” => y <= “0110011”; WHEN “0101” => y <= “1011011”; WHEN “0110” => y <= “1011111”; WHEN “0111” => y <= “1110000”; WHEN “1000” => y <= “1111111”; WHEN “1001” => y <= “1111011”; WHEN OTHERS => Y <= “1111110”; END CASE; END PROCESS;END ARCHITECTURE;

module seven_seg_dec (a, y); input [3:0] a; output [6:0] y;

reg [6:0] y;

always @(a) case (a) 0 : y = 7’b 1111110; 1 : y = 7’b 0100000; 2 : y = 7’b 1101101; 3 : y = 7’b 1111001; 4 : y = 7’b 0110011; 5 : y = 7’b 1011011; 6 : y = 7’b 1011111; 7 : y = 7’b 1110000; 8 : y = 7’b 1111111; 9 : y = 7’b 1111011; default : y = 7’b 1111110; endcaseendmodule

Page 201: PrecisionRTL Style

Boolean LogicPriority Encoder

Precision Synthesis Style Guide, 2011a Update2 201November 2011

Priority EncoderExample of an 8-bitpriority encoder.

In this case, priority isgiven to the highest bit thatis set in the input bits.

VHDL Verilog

LIBRARY ieee;USE ieee.std_logic_1164.ALL;USE ieee.numeric_std.ALL;

ENTITY priority_encoder ISPORT(a : IN unsigned(7 DOWNTO 0);

valid : OUT STD_LOGIC; y : OUT unsigned(2 DOWNTO

0));END ENTITY ;

ARCHITECTURE rtl OF priority_encoderIS

BEGIN PROCESS (a) BEGIN valid <= ‘0’; y <= “XXX”; FOR i IN 7 DOWNTO 0 LOOP IF (a(i) = ‘1’) THEN y <= to_unsigned(i,3); valid <= ‘1’; exit; END IF; END LOOP; END PROCESS;END ARCHITECTURE;

module priority_encoder (a, valid, y); input [7:0] a; output valid; output [2:0] y;

integer i; reg valid; reg [2:0] y;

always @ (a) begin valid = 0; y = 3’b X;

for (i = 0; i < 8; i = i + 1) if (a[i]) begin valid = 1; y = i; end endendmodule

Page 202: PrecisionRTL Style

Precision Synthesis Style Guide, 2011a Update2202

Boolean LogicMultiplexer

November 2011

MultiplexerExample of a generic bus width 8 to 1multiplexer. It is implemented using a casestatement.

VHDL Verilog

LIBRARY ieee;USE ieee.std_logic_1164.ALL;USE ieee.numeric_std.ALL;

ENTITY mux_8to1 IS GENERIC(width : INTEGER := 4); PORT (Sel : IN INTEGER RANGE 0 TO 7; a0,a1 : IN UNSIGNED(width-1 DOWNTO 0); a2,a3 : IN UNSIGNED(width-1 DOWNTO 0); a4,a5 : IN UNSIGNED(width-1 DOWNTO 0); a6,a7 : IN UNSIGNED(width-1 DOWNTO 0);

y : OUT UNSIGNED(width-1 DOWNTO 0));END ENTITY;

ARCHITECTURE rtl OF mux_8to1 ISBEGIN

PROCESS (Sel,a0,a1,a2,a3,a4,a5,a6,a7) BEGIN CASE Sel IS WHEN 0 => y <= a0; WHEN 1 => y <= a1; WHEN 2 => y <= a2; WHEN 3 => y <= a3; WHEN 4 => y <= a4; WHEN 5 => y <= a5; WHEN 6 => y <= a6; WHEN 7 => y <= a7; END CASE; END PROCESS;END ARCHITECTURE;

module mux_8to1 (sel, a0, a1, a2,a3, a4, a5, a6, a7,

y); parameter width = 4; input [2:0] sel; input [width - 1:0] a0, a1, a2, a3; input [width - 1:0] a4, a5, a6, a7; output [width - 1:0] y;

reg [width - 1:0] y;

always @ (sel or a0 or a1 or a2 or a3 or a4 or a5 or a6 or a7) case (sel) 0 : y = a0; 1 : y = a1; 2 : y = a2; 3 : y = a3; 4 : y = a4; 5 : y = a5; 6 : y = a6; 7 : y = a7; default : y = a0; endcaseendmodule

Page 203: PrecisionRTL Style

Boolean LogicParallel Mux

Precision Synthesis Style Guide, 2011a Update2 203November 2011

Parallel MuxExample of a parallel multiplexer. Allinputs have equal priority in a parallelMUX.

VHDL Verilog

LIBRARY ieee;USE ieee.std_logic_1164.ALL;USE ieee.numeric_std.ALL;

ENTITY parallel_mux IS PORT(a, b, c, d : IN std_logic; sel : IN unsigned(1 DOWNTO

0); muxout : OUT std_logic );END ENTITY;

ARCHITECTURE rtl OF parallel_mux ISBEGIN PROCESS (a, b, c, d, sel) IS BEGIN CASE sel IS

WHEN “00” => muxout <= a;WHEN “01” => muxout <= b;WHEN “10” => muxout <= c;WHEN OTHERS => muxout <=

d; END CASE; END PROCESS;END ARCHITECTURE;

module parallel_mux (a, b, c, d, sel, muxout); input a, b, c, d; input [1:0] sel; output muxout;

reg muxout;

always @(a or b or c or d or sel) case (sel) 2’b00 : muxout = a; 2’b01 : muxout = b; 2’b10 : muxout = c; default : muxout = d; endcaseendmodule

Page 204: PrecisionRTL Style

Precision Synthesis Style Guide, 2011a Update2204

Boolean LogicSerial Mux

November 2011

Serial MuxExample design that creates a series ofmuxes, which forms priority using ifstatements.

In this design, priority is given to z, then y,and then x.

VHDL Verilog

LIBRARY ieee;USE ieee.std_logic_1164.ALL;

ENTITY serial_mux IS PORT( a, b, c, d : IN STD_LOGIC; x, y, z : IN STD_LOGIC; outp : OUT STD_LOGIC );END ENTITY;

ARCHITECTURE rtl OF serial_mux ISBEGIN PROCESS (a, b, c, d, x, y, z)

BEGINIF z = ‘1’ THEN outp <= a;ELSIF y = ‘1’ THEN outp <= b;ELSIF x = ‘1’ THEN outp <= c;ELSE outp <= d;

END IF; END PROCESS;END ARCHITECTURE;

module serial_mux (a, b, c, d, x, y, z, outp); input a, b, c, d; input x, y, z; output outp;

reg outp;

always @(a or b or c or d or x or y or z) if (z) outp = a; else if (y) outp = b; else if (x) outp = c; else outp = d;endmodule

Page 205: PrecisionRTL Style

Precision Synthesis Style Guide, 2011a Update2 205November 2011

Chapter 7Registers

HDL synthesis produces registered and combinational logic. All combinational behavior aroundthe registers is, unless prohibited by the user, optimized automatically. The style of codingcombinational behavior, such as if-then-else and case statements, has some effect on the finalcircuit result, but the style of coding sequential behavior has significant impact on your design.

The purpose of this section is to show how sequential behavior is produced with VHDL andVerilog, so that you understand why registers are generated at certain places and not in others.

Common GuidelinesA level sensitive latch is generated anytime a signal must retain its value until being set again.An edge triggered flip-flop is generated if a signal assignment is executed only on the leading(or only on the trailing) edge of another signal. For that reason, the condition under which theassignment is done must include an edge-detecting construct. The three most added features to alatch or flip flop are the reset, set, and clock enable signals. The set and reset signal can be eithersynchronous or asynchronous, depending on how they need to function.

Synchronous Sets and ResetsAll conditional assignments to the output variable translate into combinational logic in front ofthe D-input of the flip-flop. For instance, we can make a synchronous reset on the flip-flop bydoing a conditional assignment to the output that assigns the output to zero if the reset input ishigh. Any variable meant as a synchronous set or reset should not be included in the sensitivitylist for the block.

Asynchronous Sets and ResetsIf we want the reset signal to have immediate effect on the output, but still want the regularassignment to the output to happen on the leading clock edge, we require the behavior of anasynchronous reset.

In order to have an asynchronous set or reset, the input signal MUST be in the sensitivity list. Ifit is not in the sensitivity list, the block will not be executed when the variable changes.

Asynchronous set and reset can both be used. This results in combinational logic driving the setand reset input of the flip-flop of the target signal. There can be several asynchronousconditional clauses, but any asynchronous assignments must have higher priority than thesynchronous assignments. A flip-flop is generated for each signal that is assigned in the

Page 206: PrecisionRTL Style

Precision Synthesis Style Guide, 2011a Update2206

RegistersVHDL / Verilog Differences

November 2011

synchronous signal assignment. The asynchronous clauses result in combinational logic thatdrives the set and reset inputs of the flip-flops. If there is no synchronous clause, all logicbecomes combinational.

Clock EnableIt is also possible to specify an enable signal in a process. Some technologies (specificallyXilinx and Altera) have a special enable pin on their basic flip-flop. The synthesis toolsrecognize the function of the enable from the HDL description and generate a flip-flop with anenable signal, when specified in code.

If an enable pin does not exist in the target technology a multiplexer is generated in front of thedata input of the flip-flop.

VHDL / Verilog DifferencesThe following subsections highlight some of the differences between VHDL and Verilog:

Determining the Clock EdgeIn VHDL, the EVENT attribute on a signal is the most commonly used edge-detectingmechanism. The EVENT attribute operates on a signal and returns a boolean. The result isalways FALSE, unless the signal showed a change (edge) in value. If the signal started theprocess by a change in value, the EVENT attribute is TRUE all the way through the process.The attribute STABLE is the boolean inversion of the EVENT attribute. Hence, CLK'EVENT isthe same as NOT CLK'STABLE.

Another way to generate registers in VHDL is by using the wait until statement. The wait untilclause can be used in a process, and is synthesizable, as long as all of the control paths inside theprocess contain at least one wait statement. There is no sensitivity list on this process. In VHDL,a process can have a sensitivity list or a wait statement, but not both. In this example, theprocess is executed if clk changes since clk is present in the wait condition. Also, the waitcondition can be simplified to wait until clk=’1’, since the process only starts if clkchanges, and thus clk'event is always true. Multiple wait statements per process are alsosupported as long as all of the statements have the same wait until clause.

In Verilog, the two most commonly used constructs are posedge and negedge. The posedgeconstruct detects transitions (is true) from 0 to 1. The negedge construct detects transitions from1 to 0.

In VHDL, synchronous signals are allowed to be on the sensitivity list for the process. InVerilog, only asynchronous signals appear in the sensitivity list.

Page 207: PrecisionRTL Style

RegistersVHDL / Verilog Differences

Precision Synthesis Style Guide, 2011a Update2 207November 2011

Asynchronous set and resetFor an asynchronous set or reset, both languages require the signals to be included in thesensitivity list. However, they react differently if it is left out. In VHDL, if the reset signal wasset, the process would start anytime there was a clock event, up or down. This behavior cannotbe synthesized into logic. In Verilog, the asynchronous reset would be synthesize the same as asynchronous reset.

VHDL Wait StatementsAnother way to generate registers in VHDL is by using the wait until statement. The wait

until clause can be used in a process, and is synthesizable, as long as all of the control pathsinside the process contain at least one wait statement. The following code fragment generates anedge triggered flip-flop between signal input_foo and output_foo:

There is no sensitivity list on this process. In VHDL, a process can have a sensitivity list or await statement, but not both. In this example, the process is executed if clk changes since clk ispresent in the wait condition. Also, the wait condition can be simplified to wait until

clk=’1’ ;, since the process only starts if clk changes, and thus clk'event is always true.Multiple wait statements per process are also supported as long as all of the statements have thesame wait until clause.

Precision RTL Synthesis does not support asynchronous reset behavior with wait statements. Asynchronous reset remains possible however, by describing the reset behavior after the waitstatement.

Predefined Flip-flops and LatchesFlip-flops and latches can also be generated by using predefined VHDL procedures from theexemplar package. These procedure calls cause Precision RTL Synthesis to instantiate therequired flip-flop or D-latch. There are various forms of these procedures available, includingversions with asynchronous preset and clear.

VHDL VariablesVariables (like signals) can also generate flip-flops. Since the variable is defined in the processitself, and its value never leaves the process, the only time a variable generates a flip-flop is

signal input_foo, output_foo, clk : bit ;...processbegin

wait until clk’event and clk=’1’ ;output_foo <= input_foo ;

end process ;

Page 208: PrecisionRTL Style

Precision Synthesis Style Guide, 2011a Update2208

RegistersOptimization Issues

November 2011

when the variable is used before it is assigned in a clocked process. For instance, the followingcode segment generates a three-bit shift register.

In this case, the variables a and b are used before they are assigned. Therefore, they pass theirvalues from the last run through the process, which is the assigned value delayed by one clockcycle. If the variables are assigned before they are used, you will get a different circuit:

Here, a and b are assigned before they are used, and therefore do not generate flip-flops.Instead, they generate a single wire. Only one flip-flop remains in between.

Optimization IssuesThe following list shows some of the reasons why Precision may replicate or remove registersfrom the RTL design:

• Excessive fanout: If the load is too large, the load may be split between multipledrivers, or the load may be cut and the driver duplicated.

• Moving the Flip-Flop to an Input/Output Block: If the flip flop does not use the set,reset, or clock enable pins, it can be placed into an IO block. This decreases the externalsetup time, in exchange for an increase in the internal setup time. The number of logicblocks used can also be decreased.

signal input_foo, output_foo, clk : bit ;...process (clk)

variable a, b : bit ;begin

if (clk’event and clk=’1’) thenoutput_foo <= b ;b := a ;a := input_foo ;

end if ;end process ;

signal input_foo, output_foo, clk : bit ;...process (clk)

variable a, b : bit ;begin

if (clk’event and clk=’1’) thena := input_foo ;b := a ;output_foo <= b ;

end if ;end process ;

Page 209: PrecisionRTL Style

RegistersAttributes That Affect Registers

Precision Synthesis Style Guide, 2011a Update2 209November 2011

Attributes That Affect RegistersThe following list summaries the attributes that affect register replication and IO placement:

• dont_retime: Specifies that the retiming algorithm can be disabled on individualregisters or modules.

• inff: Tells Precision Synthesis whether or not to map the first register in the input path toa register in the IO block. By default, Precision maps the first register to the IO block ifthis attribute is not present. The attribute is applied to the input port.

• iob (Xilinx only): Specifies that the placement of the register is to be forced into theIOB. This may increase the IO frequency at the possible expense of the internal chipfrequency. For bi-directional ports, you can individually control the movement of flopsusing the inff, outff, and triff attributes.

• max_fanout: Allows you to change the fanout limit on the specified net.

• outff: Tells Precision Synthesis whether or not to map the candidate register in theoutput path to a register in the IO block. By default, Precision maps the register to the IOblock if this attribute is not present. The attribute is applied to the output port.

• triff: Tells Precision Synthesis whether or not to map the candidate register in the path toa register in the IO block.

Register ExamplesThe following table shows the VHDL and Verilog examples described in this section. The codefiles are available in the Precision Synthesis software tree in the following directory:

<precision_install_dir>/shared/examples/style_guide_hdl/Registers

Table 7-1. Register Examples

Example Description

D Latch A D Latch is level sensitive and, therefore, has no clock signal.

D Latch withAsynchronous Set andReset

D Latch with an asynchronous set and reset signal. If the reset signalis high, the output will immediately become zero, and if the set ishigh, the output will become one.

Generic N-BitRegister with Enable

Generic N-bit register with a clock and a clock enable signal, but noset or reset signal.

D Flip Flop Basic D Flip Flop with no clock enable, set, or reset signals.

Page 210: PrecisionRTL Style

Precision Synthesis Style Guide, 2011a Update2210

RegistersRegister Examples

November 2011

D Flip Flop withEnable

The clock enable only allows the output to be assigned when theenable is high. It is a synchronous signal, meaning that the output willonly be set on a clock edge, regardless of when the enable signalchanges.

D Flip Flop withSynchronous Reset

The synchronous reset is checked only on a clock edge, so it is notrequired in the sensitivity list. The reset sets the output to zero when itis high.

D Flip Flop withAsynchronous Reset

The asynchronous reset sets the output to zero whenever it becomeshigh, independent of the clock-edge. It is required to be in thesensitivity list.

D Flip Flop withSynchronous Set

The synchronous set is checked only on a clock edge, so it is notrequired in the sensitivity list. The set sets the output to one when it ishigh.

D Flip Flop withAsynchronous Set

The asynchronous set sets the output to one whenever it becomeshigh, independent of the clock-edge. It is required to be in thesensitivity list.

D Flip Flop withEnable andSynchronous Reset

The enable only allows the output to be set if the enable is high. Thesynchronous reset is checked only on a clock edge, so it is notrequired in the sensitivity list.

D Flip Flop withEnable andAsynchronous Reset

The enable only allows the output to be set if the enable is high. Theasynchronous reset sets the output to zero whenever it becomes high,independent of the clock-edge.

D Flip Flop withEnable andSynchronous Set

The enable only allows the output to be set if the enable is high. Thesynchronous set is checked only on a clock edge, so it is not requiredin the sensitivity list.

D Flip Flop withEnable andAsynchronous Set

The enable only allows the output to be set if the enable is high. Theasynchronous set sets the output to one whenever it becomes high,independent of the clock-edge.

D Flip Flop withSynchronous Resetand Set

Example with both a synchronous reset and a synchronous set. Theseare both checked only after a clock edge, and do not need to appear inthe sensitivity list.

D Flip Flop withAsynchronous Resetand Set

Example with both an asynchronous reset and an asynchronous set,which both operate independent from the clock signal, and mustappear in the sensitivity list. Reset has priority over set.

D Flip Flop withEnable andSynchronous Resetand Set

The enable only allows the output to be set if the enable is high. Thereis both a synchronous reset and a synchronous set. These are bothchecked only after a clock edge, and do not need to appear in thesensitivity list. Reset has priority over set, which has priority overenable.

Table 7-1. Register Examples

Example Description

Page 211: PrecisionRTL Style

RegistersRegister Examples

Precision Synthesis Style Guide, 2011a Update2 211November 2011

D Flip Flop withEnable andAsynchronous Resetand Set

The enable only allows the output to be set if the enable is high. Thereis both an asynchronous reset and an asynchronous set, which bothoperate independent from the clock signal, and must appear in thesensitivity list.

D Flip Flop withAsynchronous Resetand Synchronous Set

The asynchronous reset sets the output to zero whenever it becomeshigh, independent of the clock-edge. It is required to be in thesensitivity list.

D Flip Flop withEnable andAsynchronous Resetand Synchronous Set

The enable only allows the output to be set if the enable is high. Theasynchronous reset sets the output to zero whenever it becomes high,independent of the clock-edge. It is required to be in the sensitivitylist.

D Flip Flop withSynchronous Resetand Asynchronous Set

The asynchronous set sets the output to one whenever it becomeshigh, independent of the clock-edge. It is required to be in thesensitivity list. The synchronous reset is checked only on a clockedge, so it is not required in the sensitivity list. The reset sets theoutput to zero when it is high.

D Flip Flop withEnable andSynchronous Resetand Asynchronous Set

The enable only allows the output to be set if the enable is high. Theasynchronous set sets the output to one whenever it becomes high,independent of the clock-edge. It is required to be in the sensitivitylist. The synchronous reset is checked only on a clock edge, so it isnot required in the sensitivity list. The reset sets the output to zerowhen it is high. Reset has priority over set, which has priority overenable.

Gated ClockConversion-AND

The AND gate driving the D Flip Flop will be converted to a D FlipFlop with Clock Enable, if the target technology supports such a FlipFlop.

Gated ClockConversion-NAND

The NAND gate driving the D Flip Flop will be converted to a D FlipFlop with Clock Enable, if the target technology supports such a FlipFlop.

Gated ClockConversion-OR

The OR gate driving the D Flip Flop will be converted to a D FlipFlop with Clock Enable, if the target technology supports such a FlipFlop.

Gated ClockConversion-NOR

The NOR gate driving the D Flip Flop will be converted to a D FlipFlop with Clock Enable, if the target technology supports such a FlipFlop.

Gated ClockConversion-CascadedClocks

The AND gates driving the Flip Flops will be converted to a D FlipFlop with Clock Enable, if the target technology supports such a FlipFlop. Logic optimization will also reduce the number of logic levels,as shown in the optimized result below.

Table 7-1. Register Examples

Example Description

Page 212: PrecisionRTL Style

Precision Synthesis Style Guide, 2011a Update2212

RegistersRegister Examples

November 2011

Right Shifter This shifter is fully synchronous with the clock edge. If the enablesignal is high, and the load signal is low, it will shift the input dataone bit to the right for the output. If the enable and load signals areboth high, it will output the input data. If the enable is low, it willlatch the output data.

Asynchronous RightShifter

This is an asynchronous right shifter with load, clear, and enablesignals.

Synchronous RightShifter

This is a synchronous right shifter with load, clear, and enablesignals.

Serial Shifter An 8-bit serial shifter that has an enable signal which, when high,stops the shifter. If the enable is low, the output data will be set to theleast significant bit of the temporary register, and the temporaryregister will be shifted right one bit.

Bi-Directional Shifter This is identical to the right shifter, except that is can shift either rightor left.

Right Logical Shifter Example of a right logical shifter. It uses a for loop to implement theshift, and a RAM to store the data that is being shifted.

Table 7-1. Register Examples

Example Description

Page 213: PrecisionRTL Style

RegistersD Latch

Precision Synthesis Style Guide, 2011a Update2 213November 2011

D LatchA D Latch is level sensitive and, therefore, has no clock signal.

This is a D Latch with an enable, and no set or reset signals.

The sensitivity list is required, and indicates that the block isexecuted whenever the signal d change. Also, since theassignment to the register q is hidden in a conditional clause, qcannot change (preserves its old value) if en is 0. If ena is 1, q isimmediately updated with the value of d, whenever thatchanges. This is the behavior of a level-sensitive latch.

In technologies where level-sensitive latches are not available, Precision RTL Synthesistranslates the initially generated latches to the gate equivalent of the latch, using acombinational loop.

VHDL Verilog

LIBRARY IEEE;USE IEEE.STD_LOGIC_1164.ALL;

ENTITY d_latch IS PORT (d, en: IN STD_LOGIC; q: OUT STD_LOGIC);END ENTITY;

ARCHITECTURE rtl OF d_latch ISBEGIN

PROCESS (d) BEGIN IF (en = ‘1’) THEN q <= d; END IF; END PROCESS;END ARCHITECTURE;

module d_latch (d, en, q);input d, en;output q;

reg q;

always @ (d)if (en)

q = d;

endmodule

Page 214: PrecisionRTL Style

Precision Synthesis Style Guide, 2011a Update2214

RegistersD Latch with Asynchronous Set and Reset

November 2011

D Latch with Asynchronous Set and ResetD Latch with an asynchronous set andreset signal. If the reset signal is high,the output will immediately becomezero, and if the set is high, the outputwill become one.

In this example, the reset signal haspriority. The extra boolean logic isadded to model the priority defined inthe model but it is typically optimizedaway during technology mapping.

VHDL Verilog

LIBRARY IEEE;USE IEEE.STD_LOGIC_1164.ALL;

ENTITY d_latch_asynch IS PORT (d, en, reset, set: IN STD_LOGIC; q: OUT STD_LOGIC);END ENTITY;

ARCHITECTURE rtl OF d_latch_asynch ISBEGIN PROCESS (d, reset, set) BEGIN IF (reset = ‘1’) THEN q <= ‘0’; ELSIF (set = ‘1’) THEN q <= ‘1’; ELSIF (en = ‘1’) THEN q <= d; END IF; END PROCESS;END ARCHITECTURE;

module d_latch_asynch (d, en, reset, set, q);input d, en, reset, set;output q;

reg q;

always @ (d or reset or set) if (reset) q = 0; else if (set) q = 1; else if (en) q = d;endmodule

Page 215: PrecisionRTL Style

RegistersGeneric N-Bit Register with Enable

Precision Synthesis Style Guide, 2011a Update2 215November 2011

Generic N-Bit Register with Enable

Generic N-bit register with a clock and a clockenable signal, but no set or reset signal.

VHDL Verilog

LIBRARY ieee;USE ieee.std_logic_1164.ALL;USE ieee.numeric_std.ALL;

ENTITY register_gen_en IS GENERIC(width : INTEGER := 4); PORT (clk, en : IN STD_LOGIC; d : IN UNSIGNED(width-1 DOWNTO 0); q : OUT UNSIGNED(width-1 DOWNTO 0));END ENTITY ;

ARCHITECTURE rtl OF register_gen_en ISBEGIN PROCESS (clk) BEGIN IF (clk’EVENT AND clk=’1’) THEN IF (en = ‘1’) THEN q <= d; END IF; END IF; END PROCESS;END ARCHITECTURE;

module register_gen_en (clk, en, d, q); parameter width = 4; input clk, en; input [width - 1:0] d; output [width - 1:0] q;

reg [width - 1:0] q;

always @(posedge clk) if (en) q <= d;endmodule

Page 216: PrecisionRTL Style

Precision Synthesis Style Guide, 2011a Update2216

RegistersD Flip Flop

November 2011

D Flip FlopBasic D Flip Flop with no clock enable, set, or reset signals.

VHDL Verilog

LIBRARY ieee;USE ieee.std_logic_1164.ALL;

ENTITY dff IS PORT(clk, d : IN STD_LOGIC; q : OUT STD_LOGIC);END ENTITY ;

ARCHITECTURE rtl OF dff ISBEGIN PROCESS (clk) BEGIN IF (clk’EVENT AND clk=’1’) THEN q <= d; END IF; END PROCESS;END ARCHITECTURE;

module dff (clk, d, q); input clk, d; output q; reg q;

always @(posedge clk) q <= d;endmodule

Page 217: PrecisionRTL Style

RegistersD Flip Flop with Enable

Precision Synthesis Style Guide, 2011a Update2 217November 2011

D Flip Flop with EnableThe clock enable only allows the output to be assignedwhen the enable is high. It is a synchronous signal,meaning that the output will only be set on a clock edge,regardless of when the enable signal changes.

VHDL Verilog

LIBRARY ieee;USE ieee.std_logic_1164.ALL;

ENTITY dff_e IS PORT (clk, d, en : IN STD_LOGIC; q : OUT STD_LOGIC);END ENTITY ;

ARCHITECTURE rtl OF dff_e ISBEGIN PROCESS(clk) BEGIN IF (clk’EVENT AND clk=’1’) THEN IF (en = ‘1’) THEN q <= d; END IF; END IF; END PROCESS;END ARCHITECTURE;

module dff_e (clk, en, d, q,); input clk, en, d; output q; reg q;

always @(posedge clk) if (en) q <= d;endmodule

Page 218: PrecisionRTL Style

Precision Synthesis Style Guide, 2011a Update2218

RegistersD Flip Flop with Synchronous Reset

November 2011

D Flip Flop with Synchronous ResetThe synchronous reset is checkedonly on a clock edge, so it is notrequired in the sensitivity list.The reset sets the output to zerowhen it is high.

VHDL Verilog

LIBRARY ieee;USE ieee.std_logic_1164.ALL;

ENTITY dff_sr IS PORT (clk, d, reset : IN STD_LOGIC; q : OUT STD_LOGIC);END ENTITY ;

ARCHITECTURE rtl OF dff_sr ISBEGIN PROCESS (clk) BEGIN IF (clk’EVENT AND clk=’1’) THEN IF reset = ‘1’ THEN q <= ‘0’; ELSE q <= d; END IF; END IF; END PROCESS;END ARCHITECTURE;

module dff_sr (clk, reset, d, q); input clk, reset, d; output q; reg q;

always @(posedge clk) if (reset) q <= 0; else q <= d;endmodule

Page 219: PrecisionRTL Style

RegistersD Flip Flop with Asynchronous Reset

Precision Synthesis Style Guide, 2011a Update2 219November 2011

D Flip Flop with Asynchronous ResetThe asynchronous reset sets the output to zerowhenever it becomes high, independent of the clock-edge. It is required to be in the sensitivity list.

VHDL Verilog

LIBRARY ieee;USE ieee.std_logic_1164.ALL;

ENTITY dff_ar IS PORT (clk, d, reset : IN STD_LOGIC; q : OUT STD_LOGIC);END ENTITY ;

ARCHITECTURE rtl OF dff_ar ISBEGIN PROCESS (clk,reset) BEGIN IF reset = ‘1’ THEN q <= ‘0’; ELSIF (clk’EVENT AND clk=’1’) THEN q <= d; ELSE NULL; END IF; END PROCESS;END ARCHITECTURE;

module dff_ar (clk, reset, d, q); input clk, reset, d; output q; reg q;

always @(posedge clk or posedge reset) if (reset) q <= 0; else q <= d;endmodule

Page 220: PrecisionRTL Style

Precision Synthesis Style Guide, 2011a Update2220

RegistersD Flip Flop with Synchronous Set

November 2011

D Flip Flop with Synchronous SetThe synchronous set is checked only on a clockedge, so it is not required in the sensitivity list.The set sets the output to one when it is high.

VHDL Verilog

LIBRARY ieee;USE ieee.std_logic_1164.ALL;

ENTITY dff_ss IS PORT (clk, d, set : IN STD_LOGIC; q : OUT STD_LOGIC);END ENTITY ;

ARCHITECTURE rtl OF dff_ss ISBEGIN PROCESS (clk) BEGIN IF (clk’EVENT AND clk=’1’) THEN IF (set = ‘1’) THEN q <= ‘1’; ELSE q <= d; END IF; END IF; END PROCESS;END ARCHITECTURE;

module dff_ss (clk, d, set, q); input clk, d, set; output q; reg q;

always @(posedge clk) if (set) q <= 1; else q <= d;endmodule

Page 221: PrecisionRTL Style

RegistersD Flip Flop with Asynchronous Set

Precision Synthesis Style Guide, 2011a Update2 221November 2011

D Flip Flop with Asynchronous SetThe asynchronous set sets the output to one whenever itbecomes high, independent of the clock-edge. It isrequired to be in the sensitivity list.

VHDL Verilog

LIBRARY ieee;USE ieee.std_logic_1164.ALL;

ENTITY dff_as IS PORT (clk, d, set : IN STD_LOGIC; q : OUT STD_LOGIC);END ENTITY ;

ARCHITECTURE rtl OF dff_as ISBEGIN PROCESS (clk, set) BEGIN IF (set = ‘1’) THEN q <= ‘1’; ELSIF (clk’EVENT AND clk=’1’)

THEN q <= d; END IF; END PROCESS;END ARCHITECTURE;

module dff_as (clk, d, set, q); input clk, d, set; output q; reg q;

always @(posedge clk or posedgeset)

if (set) q <= 1; else q <= d;endmodule

Page 222: PrecisionRTL Style

Precision Synthesis Style Guide, 2011a Update2222

RegistersD Flip Flop with Enable and Synchronous Reset

November 2011

D Flip Flop with Enable and Synchronous ResetThe enable onlyallows the output tobe set if the enable ishigh. Thesynchronous reset ischecked only on aclock edge, so it isnot required in thesensitivity list.

The reset sets theoutput to zero when itis high. This examplegives reset priority over enable.

VHDL Verilog

LIBRARY ieee;USE ieee.std_logic_1164.ALL;

ENTITY dff_sr_e IS PORT (clk, d : IN STD_LOGIC; en, reset : IN STD_LOGIC; q : OUT STD_LOGIC);END ENTITY;

ARCHITECTURE rtl OF dff_sr_e ISBEGIN PROCESS(clk) BEGIN IF (clk’EVENT AND clk=’1’) THEN IF reset = ‘1’ THEN q <= ‘0’; ELSIF en = ‘1’ THEN q <= d; END IF; END IF; END PROCESS;END ARCHITECTURE;

module dff_sr_e (clk, reset, en, d,q);

input clk, reset, en, d; output q; reg q;

always @(posedge clk) if (reset) q <= 0; else if (en) q <= d;endmodule

Page 223: PrecisionRTL Style

RegistersD Flip Flop with Enable and Asynchronous Reset

Precision Synthesis Style Guide, 2011a Update2 223November 2011

D Flip Flop with Enable and Asynchronous ResetThe enable only allows the output to be set if the enableis high. The asynchronous reset sets the output to zerowhenever it becomes high, independent of the clock-edge.

The reset signal is required to be in the sensitivity list.This example gives reset priority over enable.

VHDL Verilog

LIBRARY ieee;USE ieee.std_logic_1164.ALL;

ENTITY dff_ar_e IS PORT (clk, d : IN STD_LOGIC; en, reset : IN STD_LOGIC; q : OUT STD_LOGIC);END ENTITY ;

ARCHITECTURE rtl OF dff_ar_e ISBEGIN PROCESS(clk, reset) BEGIN IF (reset = ‘1’) THEN q <= ‘0’; ELSIF (clk’EVENT AND clk=’1’)

THEN IF (en = ‘1’) THEN q <= d; END IF; END IF; END PROCESS;END ARCHITECTURE;

module dff_ar_e (clk, rst, en, d, q); input clk, rst, en, d; output q; reg q;

always @(posedge clk or posedgerst)

if (rst) q <= 0; else if (en) q <= d;endmodule

Page 224: PrecisionRTL Style

Precision Synthesis Style Guide, 2011a Update2224

RegistersD Flip Flop with Enable and Synchronous Set

November 2011

D Flip Flop with Enable and Synchronous SetThe enable only allows the output tobe set if the enable is high. Thesynchronous set is checked only on aclock edge, so it is not required in thesensitivity list.

The set sets the output to one when itis high. This example gives resetpriority over enable.

VHDL Verilog

LIBRARY ieee;USE ieee.std_logic_1164.ALL;

ENTITY dff_ss_e IS PORT (clk,d,set,en : IN STD_LOGIC; q : OUT STD_LOGIC);END ENTITY ;

ARCHITECTURE rtl OF dff_ss_e ISBEGIN PROCESS (clk) BEGIN IF (clk’EVENT AND clk=’1’) THEN IF (set = ‘1’) THEN q <= ‘1’; ELSIF (en = ‘1’) THEN q <= d; END IF; END IF; END PROCESS;END ARCHITECTURE;

module dff_ss_e (clk, en, a, set, y); input clk, en, a, set; output y; reg y;

always @(posedge clk) if (set) y <= 1; else if (en) y <= a;endmodule

Page 225: PrecisionRTL Style

RegistersD Flip Flop with Enable and Asynchronous Set

Precision Synthesis Style Guide, 2011a Update2 225November 2011

D Flip Flop with Enable and Asynchronous SetThe enable only allows the output to be set if theenable is high. The asynchronous set sets the outputto one whenever it becomes high, independent ofthe clock-edge.

The set signal is required to be in the sensitivity list.This example gives set priority over enable.

VHDL Verilog

LIBRARY ieee;USE ieee.std_logic_1164.ALL;

ENTITY dff_as_e IS PORT (clk, d : IN STD_LOGIC; set, en : IN STD_LOGIC; q : OUT STD_LOGIC);END ENTITY ;

ARCHITECTURE rtl OF dff_as_e ISBEGIN PROCESS (clk, set) BEGIN IF (set = ‘1’) THEN q <= ‘1’; ELSIF (clk’EVENT AND clk=’1’)

THEN IF (en = ‘1’) THEN q <= d; END IF; END IF; END PROCESS;END ARCHITECTURE;

module dff_as_e (clk, d, set, en, q); input clk, d, en, set; output q; reg q;

always @(posedge clk or posedgeset)

if (set) q <= 1; else if (en) q <= d;endmodule

Page 226: PrecisionRTL Style

Precision Synthesis Style Guide, 2011a Update2226

RegistersD Flip Flop with Synchronous Reset and Set

November 2011

D Flip Flop with Synchronous Reset and SetExample with both asynchronous reset and asynchronous set. These areboth checked only after a clockedge, and do not need to appearin the sensitivity list.

VHDL Verilog

LIBRARY ieee;USE ieee.std_logic_1164.ALL;

ENTITY dff_sr_ss IS PORT (clk, d, set, reset : IN

STD_LOGIC; q : OUT STD_LOGIC);END ENTITY;

ARCHITECTURE rtl OF dff_sr_ss ISBEGIN PROCESS (clk) BEGIN IF (clk’EVENT AND clk=’1’) THEN IF (reset = ‘1’) THEN q <= ‘0’; ELSIF (set = ‘1’) THEN q <= ‘1’; ELSE q <= d; END IF; END IF; END PROCESS;END ARCHITECTURE;

module dff_sr_ss (clk, reset, set, d,q);

input clk, reset, set, d; output q; reg q;

always @(posedge clk) if (reset) q <= 0; else if (set) q <= 1; else q <= d;endmodule

Page 227: PrecisionRTL Style

RegistersD Flip Flop with Asynchronous Reset and Set

Precision Synthesis Style Guide, 2011a Update2 227November 2011

D Flip Flop with Asynchronous Reset and SetExample with both an asynchronousreset and an asynchronous set, whichboth operate independent from theclock signal, and must appear in thesensitivity list. Reset has priorityover set.

Asynchronous set and reset can bothbe used. This results incombinational logic driving the setand reset input of the flip-flop of the target signal. There can be several asynchronousconditional clauses, but any asynchronous assignments must have higher priority than thesynchronous assignments. A flip-flop is generated for each signal that is assigned in thesynchronous signal assignment. The asynchronous clauses result in combinational logic thatdrives the set and reset inputs of the flip-flops. If there is no synchronous clause, all logicbecomes combinational.

VHDL Verilog

LIBRARY ieee;USE ieee.std_logic_1164.ALL;

ENTITY dff_ar_as IS PORT (clk, d, set, reset : IN

STD_LOGIC; q : OUT STD_LOGIC);END ENTITY ;

ARCHITECTURE rtl OF dff_ar_as ISBEGIN PROCESS (clk, set, reset) BEGIN IF (reset = ‘1’) THEN q <= ‘0’; ELSIF (set = ‘1’) THEN q <= ‘1’; ELSIF (clk’EVENT AND clk=’1’)

THEN q <= d; END IF; END PROCESS;END ARCHITECTURE;

module dff_ar_as (clk, reset, set, d,q);

input clk, reset, set, d; output q; reg q;

always @(posedge clk or posedge reset or posedge set) if (reset) q <= 0; else if (set) q <= 1; else q <= d;endmodule

Page 228: PrecisionRTL Style

Precision Synthesis Style Guide, 2011a Update2228

RegistersD Flip Flop with Enable and Synchronous Reset and Set

November 2011

D Flip Flop with Enable and Synchronous Reset and SetThe enable only allowsthe output to be set if theenable is high. There isboth a synchronous resetand a synchronous set.These are both checkedonly after a clock edge,and do not need toappear in the sensitivitylist. Reset has priorityover set, which haspriority over enable.

VHDL Verilog

LIBRARY ieee;USE ieee.std_logic_1164.ALL;

ENTITY dff_sr_ss_e IS PORT (clk, d : IN STD_LOGIC; set, reset, en : IN

STD_LOGIC; q : OUT STD_LOGIC);END ENTITY ;

ARCHITECTURE rtl OF dff_sr_ss_e ISBEGIN PROCESS (clk) BEGIN IF (clk’EVENT AND clk=’1’) THEN IF (reset = ‘1’) THEN q <= ‘0’; ELSIF (set = ‘1’) THEN q <= ‘1’; ELSIF (en = ‘1’) THEN q <= d; END IF; END IF; END PROCESS;END ARCHITECTURE;

module dff_sr_ss_e (clk, en, reset,set, d, q);

input clk, en, reset, set, d; output q; reg q;

always @(posedge clk) if (reset) q <= 0; else if (set) q <= 1; else if (en) q <= d;endmodule

Page 229: PrecisionRTL Style

RegistersD Flip Flop with Enable and Asynchronous Reset and Set

Precision Synthesis Style Guide, 2011a Update2 229November 2011

D Flip Flop with Enable and Asynchronous Reset and SetThe enable only allows the outputto be set if the enable is high. Thereis both an asynchronous reset andan asynchronous set, which bothoperate independent from the clocksignal, and must appear in thesensitivity list.

Reset has priority over set, whichhas priority over enable.

VHDL Verilog

LIBRARY ieee;USE ieee.std_logic_1164.ALL;

ENTITY dff_ar_as_e IS PORT (clk, d : IN STD_LOGIC; set, reset, en : IN

STD_LOGIC; q : OUT STD_LOGIC);END ENTITY ;

ARCHITECTURE rtl OF dff_ar_as_e ISBEGIN PROCESS (clk, set, reset) BEGIN IF (reset = ‘1’) THEN q <= ‘0’; ELSIF (set = ‘1’) THEN q <= ‘1’; ELSIF (clk’EVENT AND clk=’1’)

THEN IF (en = ‘1’) THEN q <= d; END IF; END IF; END PROCESS;END ARCHITECTURE;

module dff_ar_as_e (clk, en, reset, set, d, q); input clk, en, reset, set, d; output q; reg q;

always @(posedge clk or posedge reset or posedge set) if (reset) q <= 0; else if (set) q <= 1; else if (en) q <= d;endmodule

Page 230: PrecisionRTL Style

Precision Synthesis Style Guide, 2011a Update2230

RegistersD Flip Flop with Asynchronous Reset and Synchronous Set

November 2011

D Flip Flop with Asynchronous Reset and SynchronousSet

The asynchronous reset sets the output to zerowhenever it becomes high, independent of theclock-edge. It is required to be in thesensitivity list.

The synchronous set is checked only on aclock edge, so it is not required in thesensitivity list. The set sets the output to onewhen it is high.

VHDL Verilog

LIBRARY ieee;USE ieee.std_logic_1164.ALL;

ENTITY dff_ar_ss IS PORT (clk, d, set, reset : IN

STD_LOGIC; q : OUT STD_LOGIC);END ENTITY ;

ARCHITECTURE rtl OF dff_ar_ss ISBEGIN PROCESS (clk, reset) BEGIN IF (reset = ‘1’) THEN q <= ‘0’; ELSIF (clk’EVENT AND clk=’1’)

THEN IF (set = ‘1’) THEN q <= ‘1’; ELSE q <= d; END IF; END IF; END PROCESS;END ARCHITECTURE;

module dff_ar_ss (clk, reset, set, d,q);

input clk, reset, set, d; output q; reg q;

always @(posedge clk or posedge reset) if (reset) q <= 0; else if (set) q <= 1; else q <= d;endmodule

Page 231: PrecisionRTL Style

RegistersD Flip Flop with Enable and Asynchronous Reset and Synchronous Set

Precision Synthesis Style Guide, 2011a Update2 231November 2011

D Flip Flop with Enable and Asynchronous Reset andSynchronous Set

The enable only allows the output tobe set if the enable is high. Theasynchronous reset sets the outputto zero whenever it becomes high,independent of the clock-edge. It isrequired to be in the sensitivity list.

The synchronous set is checkedonly on a clock edge, so it is notrequired in the sensitivity list. Theset sets the output to one when it ishigh. Reset has priority over set,which has priority over enable.

VHDL Verilog

LIBRARY ieee;USE ieee.std_logic_1164.ALL;

ENTITY dff_ar_ss_e IS PORT (clk, d : IN STD_LOGIC; set, reset, en : IN

STD_LOGIC; q : OUT STD_LOGIC);END ENTITY ;

ARCHITECTURE rtl OF dff_ar_ss_e ISBEGIN PROCESS (clk, reset) BEGIN IF (reset = ‘1’) THEN q <= ‘0’; ELSIF (clk’EVENT AND clk=’1’)

THEN IF (set = ‘1’) THEN q <= ‘1’; ELSIF (en = ‘1’) THEN q <= d; END IF; END IF; END PROCESS;END ARCHITECTURE;

module dff_ar_ss_e (clk, en, reset , set, d, q); input clk, en, reset, set, d; output q; reg q;

always @(posedge clk or posedge reset) if (reset) q <= 0; else if (set) q <= 1; else if (en) q <= d;endmodule

Page 232: PrecisionRTL Style

Precision Synthesis Style Guide, 2011a Update2232

RegistersD Flip Flop with Synchronous Reset and Asynchronous Set

November 2011

D Flip Flop with Synchronous Reset and AsynchronousSet

The asynchronous set sets the output toone whenever it becomes high,independent of the clock-edge. It isrequired to be in the sensitivity list. Thesynchronous reset is checked only on aclock edge, so it is not required in thesensitivity list. The reset sets the outputto zero when it is high.

VHDL Verilog

LIBRARY ieee;USE ieee.std_logic_1164.ALL;

ENTITY dff_sr_as IS PORT (clk, d, set, reset : IN

STD_LOGIC; q : OUT STD_LOGIC);END ENTITY;

ARCHITECTURE rtl OF dff_sr_as ISBEGIN PROCESS (clk, set) BEGIN IF (set = ‘1’) THEN q <= ‘1’; ELSIF (clk’EVENT AND clk=’1’)

THEN IF (reset = ‘1’) THEN q <= ‘0’; ELSE q <= d; END IF; END IF; END PROCESS;END ARCHITECTURE;

module dff_sr_as (clk, reset, set, d,q);

input clk, reset, set, d; output q; reg q;

always @(posedge clk or posedgeset)

if (set) q <= 1; else if (reset) q <= 0; else q <= d;endmodule

Page 233: PrecisionRTL Style

RegistersD Flip Flop with Enable and Synchronous Reset and Asynchronous Set

Precision Synthesis Style Guide, 2011a Update2 233November 2011

D Flip Flop with Enable and Synchronous Reset andAsynchronous Set

The enable only allowsthe output to be set if theenable is high. Theasynchronous set sets theoutput to one whenever itbecomes high,independent of the clock-edge. It is required to bein the sensitivity list. Thesynchronous reset ischecked only on a clockedge, so it is not requiredin the sensitivity list. Thereset sets the output to zero when it is high. Reset has priority over set, which has priorityover enable.

VHDL Verilog

LIBRARY ieee;USE ieee.std_logic_1164.ALL;

ENTITY dff_sr_as_e IS PORT (clk, d : IN STD_LOGIC; set, reset, en : IN

STD_LOGIC; q : OUT STD_LOGIC);END ENTITY ;

ARCHITECTURE rtl OF dff_sr_as_e ISBEGIN PROCESS (clk, set) BEGIN IF (set = ‘1’) THEN q <= ‘1’; ELSIF (clk’EVENT AND clk=’1’)

THEN IF (reset = ‘1’) THEN q <= ‘0’; ELSIF (en = ‘1’) THEN q <= d; END IF; END IF; END PROCESS;END ARCHITECTURE;

module dff_sr_as_e (clk, en, reset, set, d, q); input clk, en, reset, set, d; output q; reg q;

always @(posedge clk or posedgeset)

if (set) q <= 1; else if (reset) q <= 0; else if (en) q <= d;endmodule

Page 234: PrecisionRTL Style

Precision Synthesis Style Guide, 2011a Update2234

RegistersGated Clock Conversion-AND

November 2011

Gated Clock Conversion-ANDThe AND gate driving the D Flip Flopwill be converted to a D Flip Flop withClock Enable, if the target technologysupports such a Flip Flop.

Follow these steps:

1. compile

2. define gating clock using thecreate_clock command

3. synthesize

For additional information on gated clockconversion, see the Constraining andSynthesizing chapter of the Precision RTL Synthesis User’s Manual.

VHDL Verilog

-- How to infer gated clock:---- compile---- create_clock gate -period 10---- synthesize

library IEEE;use IEEE.std_logic_1164.all;use IEEE.numeric_std.all;

ENTITY and_gated_clk IS port ( clk, gate, din: in std_logic; dout: out std_logic );END and_gated_clk;

ARCHITECTURE rtl OF and_gated_clk ISsignal gated_clk: std_logic;begingated_clk <= clk AND gate;process (gated_clk) begin if rising_edge (gated_clk) then dout <= din; end if;end process;END RTL;

// How to infer gated clock:// - compile// - create_clock gate -period 10// - synthesize

module and_gated_clk ( clk, gate,din, dout);

input clk, gate;input din;output dout;reg dout;

wire gate_1;assign gate_1 = clk & gate;

always @ (posedge gate_1) dout <= din;

endmodule

RTL

Optimized

Page 235: PrecisionRTL Style

RegistersGated Clock Conversion-NAND

Precision Synthesis Style Guide, 2011a Update2 235November 2011

Gated Clock Conversion-NANDThe NAND gate driving the D FlipFlop will be converted to a D Flip Flopwith Clock Enable, if the targettechnology supports such a Flip Flop.

Follow these steps:

1. compile

2. define gating clock using thecreate_clock command

3. synthesize

For additional information on gatedclock conversion, see the Constrainingand Synthesizing chapter of the Precision RTL Synthesis User’s Manual.

VHDL Verilog

-- How to infer gated clock:-- - compile-- - create_clock gate -period 10-- - synthesize

library IEEE;use IEEE.std_logic_1164.all;use IEEE.numeric_std.all;

ENTITY nand_gated_clk IS port (clk, gate, din: in std_logic; dout: out std_logic );END nand_gated_clk;

ARCHITECTURE rtl OF nand_gated_clk ISsignal gated_clk: std_logic;begingated_clk <= clk NAND gate;process (gated_clk) begin

if rising_edge (gated_clk) then dout <= din;end if;

end process;END RTL;

// How to infer gated clock:// - compile// - create_clock gate -period 10// - synthesize

module nand_gated_clk ( clk, gate,din, dout);

input clk, gate;input din;output dout;reg dout;

wire gate_1;assign gate_1 = ~(clk & gate);

always @ (posedge gate_1) dout <= din;

endmodule

RTL

Optimized

Page 236: PrecisionRTL Style

Precision Synthesis Style Guide, 2011a Update2236

RegistersGated Clock Conversion-OR

November 2011

Gated Clock Conversion-ORThe OR gate driving the D Flip Flopwill be converted to a D Flip Flopwith Clock Enable, if the targettechnology supports such a FlipFlop.

Follow these steps:

1. compile

2. define gating clock using thecreate_clock command

3. synthesize

For additional information on gatedclock conversion, see the Constraining and Synthesizing chapter of the Precision RTL SynthesisUser’s Manual.

VHDL Verilog

-- How to infer gated clock:-- - compile-- - create_clock gate -period 10-- - synthesize

library IEEE;use IEEE.std_logic_1164.all;use IEEE.numeric_std.all;

ENTITY or_gated_clk IS port (clk, gate, din: in std_logic; dout: out std_logic );END or_gated_clk;

ARCHITECTURE rtl OF or_gated_clk ISsignal gated_clk: std_logic;begingated_clk <= clk OR gate;process (gated_clk) begin if rising_edge (gated_clk) then dout <= din; end if;end process;END RTL;

// How to infer gated clock:// - compile// - create_clock gate -period 10// - synthesize

module or_gated_clk ( clk, gate,din, dout);

input clk, gate;input din;output dout;reg dout;

wire gate_1;assign gate_1 = clk | gate;

always @ (posedge gate_1) dout <= din;

endmodule

RTL

Optimized

Page 237: PrecisionRTL Style

RegistersGated Clock Conversion-NOR

Precision Synthesis Style Guide, 2011a Update2 237November 2011

Gated Clock Conversion-NORThe NOR gate driving the D Flip Flopwill be converted to a D Flip Flopwith Clock Enable, if the targettechnology supports such a Flip Flop.

Follow these steps:

1. compile

2. define gating clock using thecreate_clock command

3. synthesize

For additional information on gatedclock conversion, see the Constrainingand Synthesizing chapter of the Precision RTL Synthesis User’s Manual.

VHDL Verilog

-- How to infer gated clock:-- - compile-- - create_clock gate -period 10-- - synthesize

library IEEE;use IEEE.std_logic_1164.all;use IEEE.numeric_std.all;

ENTITY nor_gated_clk ISport ( clk, gate, din: in std_logic;

dout: out std_logic);

END nor_gated_clk;

ARCHITECTURE rtl OF nor_gated_clk ISsignal gated_clk: std_logic;begingated_clk <= clk NOR gate;process (gated_clk) begin

if rising_edge (gated_clk) then dout <= din;end if;

end process;END RTL;

// How to infer gated clock:// - compile// - create_clock gate -period 10// - synthesize

module nor_gated_clk ( clk, gate,din, dout);

input clk, gate;input din;output dout;reg dout;

wire gate_1;assign gate_1 = ~(clk | gate);

always @ (posedge gate_1)dout <= din;

endmodule

RTL

Optimized

Page 238: PrecisionRTL Style

Precision Synthesis Style Guide, 2011a Update2238

RegistersGated Clock Conversion-Cascaded Clocks

November 2011

Gated Clock Conversion-Cascaded ClocksThe AND gates driving the Flip Flops will be converted to a D Flip Flop with Clock Enable, ifthe target technology supports such a Flip Flop. Logic optimization will also reduce the numberof logic levels, as shown in the optimized result below.

After the design is compiled, the gating clock must be defined using the create_clock command.For additional information on gated clock conversion, see the Constraining and Synthesizingchapter of the Precision RTL Synthesis User’s Manual.

RTL

Optimized

Page 239: PrecisionRTL Style

RegistersGated Clock Conversion-Cascaded Clocks

Precision Synthesis Style Guide, 2011a Update2 239November 2011

VHDL Verilog

-- The gated clock can be arbitrarily deep.-- All of the gated clock in the cascade-- will be converted to clock enables-- provided that all of them satisfied all-- of the requirements for successful-- conversion. However, if the first gated-- clock fails to convert, all subsequent-- gated clocks in the same chain-- would normally fail to convert as-- illustrated by the below RTL behavior.

-- How to infer gated clock:-- compile-- create_clock gate(1) -period 10-- synthesize

library ieee;use ieee.std_logic_1164.all;

entity cascaded_gated_clk is port( clk : in std_logic; din, gate: in std_logic_vector (3 downto 1); dout: out std_logic_vector (3 downto 1) );end entity cascaded_gated_clk;

architecture rtl of cascaded_gated_clk is

signal gate_1, gate_2, gate_3 :std_logic;

begin

gate_1 <= clk and gate(1); gate_2 <= gate_1 and gate(2); gate_3 <= gate_2 and gate(3);

gate_1_clocked : process begin wait until gate_1 = ‘1’; dout(1) <= din(1); end process gate_1_clocked;

gate_2_clocked : process begin wait until gate_2 = ‘1’; dout(2) <= din(2); end process gate_2_clocked;

gate_3_clocked : process begin wait until gate_3 = ‘1’; dout(3) <= din(3); end process gate_3_clocked;

end architecture rtl;

// The gated clock can be arbitrarily// deep. All of the gated clocks in// the cascade will be converted to// clock enables, provided that all of// them satisfied all of the// requirements for successful// conversion. However, if the first// gated clock fails to convert, all// subsequent gated clocks in the// same chain would normally fail to// convert as illustrated by the below// RTL behavior.

// How to infer gated clock:// - compile// - create_clock gate(1) -period 10// - synthesize

module cascaded_gated_clk ( clk, gate, din, dout);

input clk;input [3:1] gate, din;output [3:1] dout;reg [3:1] dout;

wire gate_1, gate_2, gate_3;

assign gate_1 = clk && gate[1];assign gate_2 = gate_1 && gate[2];assign gate_3 = gate_2 && gate[3];

always @(posedge gate_1)if (gate_1) dout[1] = din[1];

always @(posedge gate_2)if (gate_2) dout[2] = din[2];

always @(posedge gate_3)if (gate_3) dout[3] = din[3];

endmodule

Page 240: PrecisionRTL Style

Precision Synthesis Style Guide, 2011a Update2240

RegistersRight Shifter

November 2011

Right Shifter

This shifter is fully synchronous with theclock edge. If the enable signal is high,and the load signal is low, it will shift theinput data one bit to the right for theoutput. If the enable and load signals areboth high, it will output the input data. Ifthe enable is low, it will latch the outputdata.

VHDL Verilog

LIBRARY ieee;USE ieee.std_logic_1164.ALL;USE ieee.numeric_std.ALL;

ENTITY shift_rt IS GENERIC(width : INTEGER := 4); PORT (clk, en, load : IN STD_LOGIC; data_in : IN UNSIGNED(width-1 DOWNTO 0); data_out : OUT UNSIGNED(width-1 DOWNTO 0));END shift_rt ;

ARCHITECTURE rtl OF shift_rt ISBEGIN PROCESS (clk) BEGIN IF (clk’EVENT AND clk = ‘1’) THEN IF (en = ‘1’) THEN IF load = ‘1’ THEN data_out <= data_in; ELSE data_out <= shift_right(data_in,1); END IF; END IF; END IF; END PROCESS;END ARCHITECTURE;

module shift_rt (clk, en, load, data_in, data_out); parameter width = 4; input clk, en, load; input [width - 1:0] data_in; output [width - 1:0] data_out;

reg [width - 1:0] data_out;

always @(posedge clk) if (en) if (load) data_out <= data_in; else data_out <= data_in >> 1;endmodule

Page 241: PrecisionRTL Style

RegistersAsynchronous Right Shifter

Precision Synthesis Style Guide, 2011a Update2 241November 2011

Asynchronous Right ShifterThis is an asynchronousright shifter with load,clear, and enable signals.

Because it isasynchronous, all of thesesignals must be in thesensitivity list. The clearhas priority over the load,which has priority over theenable. If the reset is high,the output becomes allzeros, if the load is highthe output is set to theinput, and if the enable ishigh the output is shifted right one bit.

VHDL Verilog

LIBRARY IEEE;USE IEEE.STD_LOGIC_1164.ALL;USE IEEE.NUMERIC_STD.ALL;

ENTITY shift_rt_asynch IS GENERIC (width : INTEGER := 4); PORT (clk, clear, en, load : IN STD_LOGIC; a : IN UNSIGNED(width-1 DOWNTO 0); y : OUT UNSIGNED(width-1 DOWNTO 0));END ENTITY;

ARCHITECTURE rtl OF shift_rt_asynch ISBEGIN PROCESS (clk, load, clear) BEGIN IF (clear = ‘1’) THEN y <= “0000”; ELSIF (load = ‘1’) THEN y <= a; ELSIF (clk’EVENT AND clk = ‘1’) THEN IF (en = ‘1’) THEN y <= shift_right (a, 1); END IF; END IF; END PROCESS;END ARCHITECTURE;

module shift_rt_asynch (clk, enable, load, clear, a, y); parameter width = 4;

input clk, enable, load, clear; input [width - 1:0] a; output [width - 1:0] y;

reg [width - 1:0] y;

always @(posedge clk or posedge load or posedge clear) if (clear) y <= 0; else if (load) y <= a; else if (enable) y <= y >> 1;endmodule

Page 242: PrecisionRTL Style

Precision Synthesis Style Guide, 2011a Update2242

RegistersSynchronous Right Shifter

November 2011

Synchronous Right ShifterThis is a synchronous right shifter withload, clear, and enable signals.

The clear has priority over the load,which has priority over the enable. Ifthe reset is high, the output becomes allzeros, if the load is high the output isset to the input, and if the enable is highthe output is shifted right one bit.

VHDL Verilog

LIBRARY IEEE;USE IEEE.STD_LOGIC_1164.ALL;USE IEEE.NUMERIC_STD.ALL;

ENTITY shift_rt_synch IS GENERIC (width : INTEGER := 4); PORT (clk, clear, en, load : IN

STD_LOGIC;a : IN UNSIGNED(width-1 DOWNTO

0);y : OUT UNSIGNED(width-1 DOWNTO

0));END ENTITY;

ARCHITECTURE rtl OF shift_rt_synch ISBEGIN PROCESS (clk) BEGIN IF (clear = ‘1’) THEN y <= “0000”; ELSIF (load = ‘1’) THEN y <= a; ELSIF (clk’EVENT AND clk = ‘1’)

THEN IF (en = ‘1’) THEN y <= shift_right (a, 1); END IF; END IF; END PROCESS;END ARCHITECTURE;

module shift_rt_synch (clk, en, load, clear, a, y); parameter width = 4; input clk, en, load, clear; input [width - 1:0] a; output [width - 1:0] y;

reg [width - 1:0] y;

always @(posedge clk) if (clear) y <= 0; else if (load) y <= a; else if (en) y <= y >> 1;endmodule

Page 243: PrecisionRTL Style

RegistersSerial Shifter

Precision Synthesis Style Guide, 2011a Update2 243November 2011

Serial Shifter

An 8-bit serial shifter that has an enable signal which, when high, stops the shifter. If theenable is low, the output data will be set to the least significant bit of the temporary register,and the temporary register will be shifted right one bit.

The input bit ’a’ is placed in the most significant bit of the temporary register after the bits areshifted right.

VHDL Verilog

LIBRARY IEEE;USE IEEE.STD_LOGIC_1164.ALL;USE IEEE.NUMERIC_STD.ALL;

ENTITY shift_serial IS PORT (clk, en, a: IN STD_LOGIC; y: OUT STD_LOGIC);END ENTITY;

ARCHITECTURE rtl OF shift_serial ISSIGNAL temp: UNSIGNED(7 DOWNTO 0);BEGIN PROCESS (clk, en) BEGIN IF (clk’EVENT AND clk = ‘1’)

THENIF(en = ‘1’) THEN temp <= shift_right(temp, 1);

temp(7) <= a;END IF;

END IF;

y <= temp(0);

END PROCESS;END ARCHITECTURE;

module shift_serial (a, clk, en, y); input a, clk, en; output y; reg [7:0] temp; always @(posedge clk) begin if (en) begin temp = temp >> 1; temp[7] = a; end end assign y = temp[0];endmodule

Page 244: PrecisionRTL Style

Precision Synthesis Style Guide, 2011a Update2244

RegistersBi-Directional Shifter

November 2011

Bi-Directional ShifterThis is identical tothe right shifter,except that is canshift either right orleft.

The direction of theshift is determinedby the input bit ’rt’.If rt is high, it shiftsright; if it is low, itshifts left.

VHDL Verilog

LIBRARY ieee;USE ieee.std_logic_1164.ALL;USE ieee.numeric_std.ALL;

ENTITY shift_bi IS GENERIC(width : INTEGER := 4); PORT (clk, en, load, rt : IN

STD_LOGIC; data_in : IN UNSIGNED(width-

1 DOWNTO 0); data_out : OUT

UNSIGNED(width-1 DOWNTO 0));END shift_bi ;

ARCHITECTURE rtl OF shift_bi ISBEGIN PROCESS (clk) BEGIN IF (clk’EVENT AND clk = ‘1’) THEN IF (en = ‘1’) THEN IF load = ‘1’ THEN data_out <= data_in; ELSIF rt = ‘1’ THEN data_out <=

shift_right(data_in,1); ELSE data_out <=

shift_left(data_in,1); END IF; END IF; END IF; END PROCESS;END ARCHITECTURE;

module shift_bi (clk, en, load, rt, data_in, data_out); parameter width = 4; input clk, en, load, rt; input [width - 1:0] data_in; output [width - 1:0] data_out;

reg [width - 1:0] data_out;

always @(posedge clk) if (en) if (load) data_out <= data_in; else if (rt)

data_out <= data_in >>1;

elsedata_out <= data_in <<

1;endmodule

Page 245: PrecisionRTL Style

RegistersRight Logical Shifter

Precision Synthesis Style Guide, 2011a Update2 245November 2011

Right Logical ShifterExample of a right logical shifter. It uses a for loop to implement the shift, and a RAM to storethe data that is being shifted.

VHDL Verilog

LIBRARY ieee;USE ieee.std_logic_1164.ALL;USE ieee.numeric_std.ALL;

ENTITY shift_right_logical ISGENERIC ( delay_max : INTEGER := 15;

data_width : INTEGER := 8);

PORT( clk : IN STD_LOGIC; data_in : IN UNSIGNED (data_width-1 DOWNTO

0); delay : IN INTEGER RANGE

delay_max-1 DOWNTO 0; data_out : OUT UNSIGNED (data_width-1 DOWNTO

0));END ENTITY;

ARCHITECTURE rtl OF shift_right_logicalIS

TYPE srltype IS ARRAY(delay_max-1DOWNTO0) OF UNSIGNED(data_width-1 DOWNTO0);

SIGNAL internal : srltype;BEGIN

PROCESS (clk) BEGIN IF (clk’EVENT AND clk = ‘1’) THEN

internal <= internal (delay_max-2DOWNTO 0) & data_in ;

END IF;END PROCESS;

data_out <= internal(delay);

END ARCHITECTURE;

module shift_right_logical (clk, delay, data_in, data_out);

parameter max_delay = 15; parameter delay_width = 4; parameter data_width = 8;

input clk; input [0:delay_width] delay; input [0:data_width] data_in; output [0:data_width] data_out;

reg [0:data_width-1] shift [max_delay-1:0]; integer i;

always @(posedge clk) begin for (i = (max_delay-1); i>0; i=i-1) begin shift[i] <= shift[i-1]; end shift[0] <= data_in; end

assign data_out = shift[delay];

endmodule

Page 246: PrecisionRTL Style

Precision Synthesis Style Guide, 2011a Update2246

RegistersRight Logical Shifter

November 2011

Page 247: PrecisionRTL Style

Precision Synthesis Style Guide, 2011a Update2 247November 2011

Chapter 8Memory

Precision RTL Synthesis detects a RAM or ROM from the style of the RTL code at atechnology-independent level, then maps the element to a generic module in the RTL databaseat Compile time. During the technology mapping phase of synthesis, Precision maps the genericRAM or ROM module to the equivalent Vendor-specific implementation.

Common GuidelinesThe following subsections describes some general guidelines for inferring memories withinPrecision. Although Precision may infer the memory on compile, it may not implement thememory within the technology until that specific memory configuration is supported. Refer tothe technology specific sections in the Reference Manual for more information of technologyspecific implementations of memories.

Single Port RAMsPrecision supports numerous single port RAM configurations from asynchronous to registeringthe datain, address, and dataout line.

Dual Port RAMsA dual-port RAM such as a FIFO-type RAM with a separately clocked input and output is oftenused to buffer data transfers between two clock domains that are operating at differentfrequencies.

Resets for MemoriesPrecision supports 2 types of resets for memories:

1. Reset that clear the contents of memory.

For this type of memory, Precision creates any necessary glue logic for resetimplementation.

2. Reset that clear the output registers on read ports of the memory.

For this type of memory, resets are supported through the use of builtin reset pin(typically the sync pin) present in the RAM cell of the FPGA device.

Page 248: PrecisionRTL Style

Precision Synthesis Style Guide, 2011a Update2248

MemoryCommon Guidelines

November 2011

ROMsYou can implement ROM behavior in the HDL source code with CASE statements or you canspecify the ROM as an array of constants. Precision RTL Synthesis infers both synchronous andasynchronous ROM. The circuit is first mapped to technology-independent modgen ROMmodule, then to the technology-specific cell(s). By default, the minimum size of a detectedROM is 64 unique addressed memory locations.

Precision Synthesis utilizes a smart algorithm that absorbs registers into an asynchronous ROMoutput, thereby enabling ROM to block RAM mapping. Additionally, the critical timing path ismore predictable when mapping to RAM instead of using conventional ROM decoders. This isbecause the timing is mostly constrained by READ/WRITE operations and not the levels ofcombinational logic.

General Coding Guidelines for ROM InferenceROMs can be modeled by different methodologies. Precision Synthesis supports a wide rangeof coding styles. It is always helpful to understand and follow the following coding guidelineswhen modeling a ROM.

• Determine what type of ROM, e.g. Synchronous or Asynchronous

• Determine the mapping technology and its specific hardware architectures

• Determine whether or not ROM values require optimizations during synthesis, e.g.CASE Statement would be used instead of the Explicit constant arrays if you would likePrecision Synthesis to optimize these ROM values

Smart ROM to RAM Inference and Mapping AlgorithmsIn general, most if not all, block RAMs have synchronous read and write operations. Hence, inorder to successfully map any type of hardware into block RAMs, the output port must besynchronous. In FPGA designs, it is quite common to have ROM hardware with anasynchronous output port. In fact, most of the ROMs do have an asynchronous output port,thereby limiting them from being mapped into Block RAMs.

Page 249: PrecisionRTL Style

MemoryCommon Guidelines

Precision Synthesis Style Guide, 2011a Update2 249November 2011

Figure 8-1. Asynchronous ROM Mapped into Block RAM

To minimize hardware incompatibility and increase the ROM to RAM mapping rate, PrecisionSynthesis has an intelligent algorithm where it will automatically pull in available registersthrough the levels of logic that the ROM drives, as shown in Figure 8-1.

Controlling ROM to RAM Mapping OptionsYou can control ROM to block RAM mapping options by inserting either an attribute or pragmainto the HDL source file. By default, the mapping option will be decided by Precision Synthesismapping heuristics, depending on the address size and depth of the ROM. Here are the codesnippet examples of how you can set the attribute/pragma to control the mapping options.

Figure 8-2. How to Set rom_block Attribute in VHDLentity rom_to_blockram is generic ( addr_width_c : integer := 6; data_width_c : integer := 16); port(clk : in std_logic; addr : in std_logic_vector(addr_width_c-1 downto 0); dout : out std_logic_vector(data_width_c-1 downto 0) );end entity rom_to_blockram;

architecture rtl of rom_to_blockram is signal mem : std_logic_vector(data_width_c-1 downto 0); signal reg_addr : std_logic_vector(addr_width_c-1 downto 0); attribute rom_block : boolean; attribute rom_block of mem : signal is TRUE;begin

Page 250: PrecisionRTL Style

Precision Synthesis Style Guide, 2011a Update2250

MemoryCommon Guidelines

November 2011

Figure 8-3. How to Set rom_block Attribute in Verilog

Suggested Coding Techniques for RAM and ROM

VHDL Coding Techniques

Using the CASE Statement

Figure 8-4. VHDL ROM Implemented Using CASE Statement

`define WIDTH_A 6`define WIDTH_D 16`define RAM_DEPTH 256module rom_to_blockram ( addr, clk, dout ); input [`WIDTH_A-1:0] addr; input clk; reg [`WIDTH_A-1:0] reg_addr; reg [`WIDTH_D-1:0] mem; output reg [`WIDTH_D-1:0] dout;

//pragma attribute mem rom_block TRUEalways @ (posedge clk) begin

architecture rtl of rom_to_blockram is signal mem : std_logic_vector(data_width_c-1 downto 0); signal reg_addr : std_logic_vector(addr_width_c-1 downto 0); attribute rom_block : boolean; attribute rom_block of mem : signal is TRUE;begin process (clk) begin if (clk'event and clk = '1') then dout <= mem ; reg_addr <= addr; end if; end process;

process (reg_addr) begin CASE reg_addr IS WHEN "000000" => mem <= "1111101100110100"; WHEN "000001" => mem <= "0000101011011110"; WHEN "000010" => mem <= "1101110110101000"; WHEN "000011" => mem <= "1101110111010110"; WHEN "000100" => mem <= "0111101000000010"; WHEN "000101" => mem <= "0011110000111010"; WHEN "000110" => mem <= "0110101010111000";

Page 251: PrecisionRTL Style

MemoryCommon Guidelines

Precision Synthesis Style Guide, 2011a Update2 251November 2011

VHDL Explicit Constant Arrays

Figure 8-5. VHDL ROM Implement Using Array of Constantsentity rom_to_ram_const is port(clk : in std_logic; addr : in std_logic_vector(7 downto 0); data_out : out std_logic_vector(15 downto 0) );end entity rom_to_ram_const;

architecture rtl of rom_to_ram_const istype mem_type is array (15 downto 0) of std_logic_vector(15 downto 0) ;

CONSTANT mem : mem_type := ((“0000000000000001”),(“0000000000000010”),(“0000000000000100”),(“0000000000001000”),(“0000000000010000”),(“0000000000100000”),(“0000000001000000”),(“0000000010000000”),(“0000000100000000”),(“0000001000000000”),(“0000010000000000”),(“0000100000000000”),(“0001000000000000”),(“0010000000000000”),(“0100000000000000”),

Page 252: PrecisionRTL Style

Precision Synthesis Style Guide, 2011a Update2252

MemoryCommon Guidelines

November 2011

VHDL Memory Initialization

Figure 8-6. VHDL Memory Initialization ExampleLIBRARY IEEE ;USE IEEE.std_logic_1164.ALL ;USE IEEE.std_logic_unsigned.ALL ;USE STD.textio.ALL ;USE IEEE.std_logic_textio.ALL ;

ENTITY ram_synch IS GENERIC (d_width : INTEGER := 16 ; a_width : INTEGER := 8 ; INIT_FILE_FORMAT_HEX : boolean := true ) ;

PORT (data_in : IN std_logic_vector(d_width-1 DOWNTO 0) ; address : IN std_logic_vector(a_width-1 DOWNTO 0) ; wr_en, inclock, outclock : IN STD_LOGIC ; dout : OUT std_logic_vector(d_width-1 DOWNTO 0) );END ENTITY ;

ARCHITECTURE infer OF ram_synch ISTYPE mem_type IS ARRAY (2**a_width DOWNTO 0) OF std_logic_vector(d_width-1 DOWNTO 0);

SIGNAL address_save : std_logic_vector(a_width-1 DOWNTO 0) ;

FUNCTION initmem RETURN mem_type IS VARIABLE i : NATURAL ; VARIABLE depth : INTEGER := 2**a_width ; VARIABLE value : LINE ; VARIABLE data : std_logic_vector(d_width-1 downto 0) ; VARIABLE memt : mem_type ; FILE initfile : text OPEN READ_MODE is “D:\Temp\ram_init.txt” ;

BEGIN WHILE NOT endfile(initfile) AND i <= depth-1 LOOP readline(initfile,value); IF (INIT_FILE_FORMAT_HEX = true) THEN hread(value,data) ; ELSE read(value,data) ; END IF ; memt(i) := data ; i := i + 1 ; END LOOP ; RETURN memt ; END initmem ;

SIGNAL mem : mem_type := initmem ;BEGIN

ram : PROCESS (inclock,outclock) BEGIN IF (inclock = ‘1’ AND inclock’EVENT) THEN IF (wr_en = ‘1’) THEN mem(CONV_INTEGER(address_save)) <= data_in ; END IF ; address_save <= address ; END IF ;

IF (outclock = ‘1’ AND outclock’EVENT) THEN dout <= mem(CONV_INTEGER(address_save)) ; END IF ;

END PROCESS ram ;

END ARCHITECTURE ;

Page 253: PrecisionRTL Style

MemoryCommon Guidelines

Precision Synthesis Style Guide, 2011a Update2 253November 2011

Verilog Coding Techniques

Using the CASE Statement

Figure 8-7. Verilog ROM Using CASE Statement`define WIDTH_A 6`define WIDTH_D 16`define RAM_DEPTH 256module rom_to_blockram ( addr, clk, dout ); input [`WIDTH_A-1:0] addr; input clk; reg [`WIDTH_A-1:0] reg_addr; reg [`WIDTH_D-1:0] mem; output reg [`WIDTH_D-1:0] dout;

//pragma attribute mem rom_block TRUEalways @ (posedge clk) begin dout <= mem; reg_addr <= addr;end

always @(reg_addr ) begin case (reg_addr )

6'b000000 : mem = 16'b1111101100110100; 6'b000001 : mem = 16'b0000101011011110; 6'b000010 : mem = 16'b1101110110101000; 6'b000011 : mem = 16'b1101110111010110; 6'b000100 : mem = 16'b0111101000000010; 6'b000101 : mem = 16'b0011110000111010; 6'b000110 : mem = 16'b0110101010111000; 6'b000111 : mem = 16'b0101001110110100; 6'b001000 : mem = 16'b0011111110111110; 6'b001001 : mem = 16'b1111100110000100; 6'b001010 : mem = 16'b0111100111101100; 6'b001011 : mem = 16'b1111100101101000; 6'b001100 : mem = 16'b1101101100111000; 6'b001101 : mem = 16'b0110110111100100; 6'b001110 : mem = 16'b1000001011100010; 6'b001111 : mem = 16'b1111110010111000; 6'b010000 : mem = 16'b1000010100110000; 6'b010001 : mem = 16'b0010100010111000; 6'b010010 : mem = 16'b1010101010101010; 6'b010011 : mem = 16'b1111010100010100; 6'b010100 : mem = 16'b1110001110000100; 6'b010101 : mem = 16'b0111010000010000; 6'b010110 : mem = 16'b1110000000110010; 6'b010111 : mem = 16'b0010111001010000; 6'b011000 : mem = 16'b0100100011001100; 6'b011001 : mem = 16'b0011010110111010; 6'b011010 : mem = 16'b0101100100101100; 6'b011011 : mem = 16'b1101000111111000; 6'b011100 : mem = 16'b0101100010001100; 6'b011101 : mem = 16'b1010001011001100; 6'b011110 : mem = 16'b1001011101111000;

6'b011111 16'b0111011100010000

Page 254: PrecisionRTL Style

Precision Synthesis Style Guide, 2011a Update2254

MemoryCommon Guidelines

November 2011

Verilog Explicit Constant Arrays

Figure 8-8. Verilog ROM Using Array of Constantsmodule rom_to_ram_const (clk, addr, data_out);input logic clk;input logic [7:0] addr;output logic [15:0] data_out;

typedef logic [15:0] mem_type [15:0];const mem_type mem = {16'b0000000000000001,16'b0000000000000010,16'b0000000000000100,16'b0000000000001000,16'b0000000000010000,16'b0000000000100000,16'b0000000001000000,16'b0000000010000000,16'b0000000100000000,16'b0000001000000000,16'b0000010000000000,16'b0000100000000000,16'b0001000000000000,16'b0010000000000000,16'b0100000000000000,16'b1000000000000000};//pragma attribute mem rom_block 1always_ff @(posedge clk)begin data_out <= mem[integer'(addr)];endendmodule

Page 255: PrecisionRTL Style

MemoryCommon Guidelines

Precision Synthesis Style Guide, 2011a Update2 255November 2011

The $readmemh Function

Figure 8-9. Verilog ROM Initialization Using $readmemh Function

The $readmemb Function

Figure 8-10. Verilog ROM Initialization Using $readmemb Function

‘define addr_width 8‘define data_width 16module readmemh( input clk, rst, input [‘addr_width-1:0] addr, output reg [‘data_width-1:0] dataout);

reg [‘addr_width-1:0] reg_addr;//pragma attribute mem rom_block 0reg [‘data_width-1:0] mem[0:2**‘addr_width-1];

initial begin// Make sure to provide the actual physical path for the binary file$readmemh("./rom_init.hex", mem);end

always@(posedge clk) begin if (rst) reg_addr <= 0; else reg_addr <= addr;end

always@(posedge clk)

‘define addr_width 8‘define data_width 16module readmemb( input clk, rst, input [‘addr_width-1:0] addr, output reg [‘data_width-1:0] dataout);

reg [‘addr_width-1:0] reg_addr; reg [‘data_width-1:0] mem[0:2**‘addr_width-1]; //pragma attribute mem rom_block 1

initial begin // Make sure to provide the actual physical path for the binary file $readmemb("./rom_init.bin", mem); end

always@(posedge clk) begin if (rst) reg_addr <= 0; else reg_addr <= addr; end

always@(posedge clk)d t t < [ dd ]

Page 256: PrecisionRTL Style

Precision Synthesis Style Guide, 2011a Update2256

MemoryCommon Guidelines

November 2011

Byte-Enable MemoriesSome FPGA devices have memory resources that have byte-enable pins control writing data toa selected byte, instead of the entire data width. Precision has enhanced RAM inference supportof byte-enable RAM.

The example below of a 16-bit data word RAM will write to all 16 bits during a write cycle:

always @(posedge clk) begindout = mem[addr];if (WE) begin

mem [addr][15:0] = din [15:0];end

end

The code can be restructured to select the memory byte, or bytes, enabled during a write cycle:

always @(posedge clk) begindout = mem[addr];if (WE) begin

if(byteena[0]) mem [addr][7:0] = din [7:0];if(byteena[1]) mem [addr][15:8] = din [15:8];

endend

Supported Byte-Enable Device Families

Inferring Byte-Enabled RAM in PrecisionByte-enabled RAM inference and implementation occurs during both the Compile andSynthesize stages in the Precision flow.

Table 8-1. Supported Byte-Enable Device Families

Vendor Device Family

Altera

Stratix II

Stratix III

Stratix IV

Xilinx

Virtex-4

Virtex-5

Virtex-6

Page 257: PrecisionRTL Style

MemoryCommon Guidelines

Precision Synthesis Style Guide, 2011a Update2 257November 2011

Compile Stage Operations• Precision infers byte-enable pins during the Compile stage

• Precision creates the appropriate byte-enable glue logic to pass to the Synthesize stage.The type of glue logic depends on the following memory attributes:

o Read-First or Write-First

o Byte-enable has overlapping conditions

o Single or dual port configuration

Synthesis Stage OperationsDuring synthesis, Precision detects the byte enable functionality and maps the RAM to theFPGA technology RAM cell using its dedicated byte-enable port.

For Altera’s altsyncram cell, Precision makes use of the separate byte enable pin named“.byteena_a”.

For Xilinx BRAMs, Precision makes use of the technology cell’s write-enable pins (4 areavailable) as the byte-enables.

Supported Byte-Enable RTL Coding StylesSeveral characteristics of byte-enabled memory, as described in the RTL, determine how thememory and respective glue logic are inferred in Precision:

• Write mode — determines the behavior of the data available on the output after a write

o Write First — outputs the newly written data onto the output bus

o Read First — outputs the previously stored data while new data is being written

o No Change — maintains the output previously generated by a read operation

• Enable priority versus independent byte-write — determines the priority of enable pinswhen multiple byte-enable pins control different data bytes of a single memory address.If there is no explicit priority, then each enable pin is considered an “independent byte-write enable”.

• Overlapping conditions — when a single byte-wide enable controls the same addressspace controlled by another multi-byte-wide enable

• Single or Dual Port — determines whether the memory has independent access ports forread and write operations.

Page 258: PrecisionRTL Style

Precision Synthesis Style Guide, 2011a Update2258

MemoryCommon Guidelines

November 2011

Byte-Enabled Coding Style SamplesThe following are different RTL coding examples of byte-write enable memories with thecharacteristics described previously.

Read First Memory Styles

Read First, Independant Byte-Enable, Single Port

CASE Statement

module byte_ram (clk, we, byteena, addr, din, dout);

parameter datawidth = 32;parameter addrwidth = 10;parameter mem_depth = (2**addrwidth)-1;

input clk, we;input [3:0] byteena;input [datawidth-1:0] din;input [addrwidth-1:0] addr;output reg [datawidth-1:0] dout;

reg [datawidth-1:0] mem [0:mem_depth];

always @(posedge clk) begindout = mem[addr];if (we)

casex (byteena[3:0]) // synopsys parallel_case full_case4'bxxx1: mem [addr][7:0] = din [7:0];4'bxx1x: mem [addr][15:8] = din [15:8];4'bx1xx: mem [addr][23:16] = din [23:16];4'b1xxx: mem [addr][31:24] = din [31: 24];

endcaseend

endmodule

IF Statements

module byte_ram (clk, we, byteena, addr, din, dout);

parameter datawidth = 16;parameter addrwidth = 10;parameter mem_depth = (2**addrwidth)-1;

input clk, we;input [1:0] byteena;input [datawidth-1:0] din;input [addrwidth-1:0] addr;output reg [datawidth-1:0] dout;

reg [datawidth-1:0] mem [0:mem_depth];

always @(posedge clk) begindout = mem[addr];if (we)if(byteena[0]) mem[addr][7:0] = din[7:0];

Page 259: PrecisionRTL Style

MemoryCommon Guidelines

Precision Synthesis Style Guide, 2011a Update2 259November 2011

else if(byteena[1]) mem[addr][15:8] = din[15:8];end

endmodule

Read First, Priority-Enable, Single Port

module byte_ram (clk, wen, byteena, addr, din, dout);

parameter datawidth = 32;parameter addrwidth = 10;parameter mem_depth = (2**addrwidth)-1;

input clk, wen;input [3:0] byteena;input [datawidth-1:0] din;input [addrwidth-1:0] addr;output reg [datawidth-1:0] dout;

reg [datawidth-1:0] mem [0:mem_depth];

always @(posedge clk) begindout = mem[addr];if(wen) begin

if (byteena[0]) mem[addr][7:0] = din[7:0];else if(byteena[1]) mem[addr][15:8] = din[15:8];else if(byteena[2]) mem[addr][23:16] = din[23:16];else if(byteena[3]) mem[addr][31:24] = din[31:24];

endend

endmodule

Read First/ Independent Byte-Enable / Overlapping Conditions / Single Port

module byte_ram (clk, we, byteena, addr, din1, din2, dout);

parameter datawidth = 16;parameter addrwidth = 10;parameter mem_depth = (2**addrwidth)-1;

input clk, we;input [1:0] byteena;input [datawidth-1:0] din1, din2;input [addrwidth-1:0] addr;output reg [datawidth-1:0] dout;

reg [datawidth-1:0] mem [0:mem_depth];

always @(posedge clk) begindout = mem[addr];if (we)if(byteena[0]) mem[addr][7:0] = din1;

else if(byteena[1]) mem[addr] = din2;end

endmodule

Page 260: PrecisionRTL Style

Precision Synthesis Style Guide, 2011a Update2260

MemoryCommon Guidelines

November 2011

Read First / Independent Byte-Enable / Overlapping Conditions / Dual Port

module byte_ram (clk, we, byteena, addr1, addr2, din1, din2, dout);

parameter datawidth = 16;parameter addrwidth = 10;parameter mem_depth = (2**addrwidth)-1;

input clk, we;input [1:0] byteena;input [datawidth-1:0] din1, din2;input [addrwidth-1:0] addr1, addr2;output reg [datawidth-1:0] dout;

reg [datawidth-1:0] mem [0:mem_depth];

always @(posedge clk) begindout = mem[addr1];if (we)if(byteena[0]) mem[addr1][7:0] = din1;

else if(byteena[1]) mem[addr2] = din2;end

endmodule

Read First / Independent Byte-Enable / Partial addresses Dual Port

module byte_ram (clk, we, byteena, addr1, addr2, din1, din2, dout);

parameter datawidth = 16;parameter addrwidth = 10;parameter mem_depth = (2**addrwidth)-1;

input clk, we;input [1:0] byteena;input [datawidth-1:0] din1, din2;input [addrwidth-1:0] addr1, addr2;output reg [datawidth-1:0] dout;

reg [datawidth-1:0] mem [0:mem_depth];

always @(posedge clk) begindout = mem[addr1];if (we)if(byteena[0]) mem[addr1][7:0] = din1;

else if(byteena[1]) mem[addr2] [15:8] = din2;

end

endmodule

Page 261: PrecisionRTL Style

MemoryCommon Guidelines

Precision Synthesis Style Guide, 2011a Update2 261November 2011

Write First Memory Styles

Write First / Independent Byte Write / Single Port

Using CASEX Statement

module byte_ram (clk, we, byteena, addr, din, dout);

parameter datawidth = 16;parameter addrwidth = 10;parameter mem_depth = (2**addrwidth)-1;

input clk, we;input [1:0] byteena;input [datawidth-1:0] din;input [addrwidth-1:0] addr;output reg [datawidth-1:0] dout;

reg [datawidth-1:0] mem [0:mem_depth];

always @(posedge clk) beginif (we)

casex (byteena[1:0])2'bx1: mem [addr][7:0] = din [7:0];2'b1x: mem [addr][15:8] = din [15:8];

endcase

dout = mem[addr];end

endmodule

Using the IF Construct

module byte_ram (clk, we, byteena, addr, din, dout);

parameter datawidth = 16;parameter addrwidth = 10;parameter mem_depth = (2**addrwidth)-1;

input clk, we;input [1:0] byteena;input [datawidth-1:0] din;input [addrwidth-1:0] addr;output reg[datawidth-1:0] dout;

reg [datawidth-1:0] mem [0:mem_depth];

always @(posedge clk) beginif (we)if(byteena[0]) mem[addr][7:0] = din[7:0];if(byteena[1]) mem[addr][15:8] = din[15:8];

dout = mem[addr];end

endmodule

Page 262: PrecisionRTL Style

Precision Synthesis Style Guide, 2011a Update2262

MemoryCommon Guidelines

November 2011

Write First / Priority Enable / Single Port

module byte_ram (clk, wen, byteena, addr, din, dout);

parameter datawidth = 32;parameter addrwidth = 10;parameter mem_depth = (2**addrwidth)-1;

input clk, wen;input [3:0] byteena;input [datawidth-1:0] din;input [addrwidth-1:0] addr;output reg [datawidth-1:0] dout;

reg [datawidth-1:0] mem [0:mem_depth];

always @(posedge clk) beginif(wen)if(byteena[0]) mem[addr][7:0] = din[7:0];

else if(byteena[1]) mem[addr][15:8] = din[15:8];else if(byteena[2]) mem[addr][23:16] = din[23:16];else if(byteena[3]) mem[addr][31:24] = din[31:24];

dout = mem[addr];endendmodule

Write First / Independent Byte-Write / Overlapping conditions / Single Port

module byte_ram (clk, we, byteena, addr, din1, din2, dout);

parameter datawidth = 16;parameter addrwidth = 10;parameter mem_depth = (2**addrwidth)-1;

input clk, we;input [1:0] byteena;input [datawidth-1:0] din1, din2;input [addrwidth-1:0] addr;output reg [datawidth-1:0] dout;

reg [datawidth-1:0] mem [0:mem_depth];

always @(posedge clk) beginif (we)if(byteena[0]) mem[addr][7:0] = din1;if(byteena[1]) mem[addr] = din2;dout = mem[addr];

endendmodule

Write First / Independent Byte-Write / Overlapping Conditions / Dual Port

module byte_ram (clk, we, byteena, addr1, addr2, din1, din2, dout);

parameter datawidth = 16;

Page 263: PrecisionRTL Style

MemoryVHDL/Verilog Differences

Precision Synthesis Style Guide, 2011a Update2 263November 2011

parameter addrwidth = 10;parameter mem_depth = (2**addrwidth)-1;

input clk, we;input [1:0] byteena;input [datawidth-1:0] din1, din2;input [addrwidth-1:0] addr1, addr2;output reg [datawidth-1:0] dout;

reg [datawidth-1:0] mem [0:mem_depth];

always @(posedge clk) beginif (we)if(byteena[0]) mem[addr1][7:0] = din1;if(byteena[1]) mem[addr2] = din2;

dout = mem[addr1];end

endmodule

Write First / Independent Byte-Enable / Partial addresses / Dual Port

module byte_ram (clk, we, byteena, addr1, addr2, din1, din2, dout);

parameter datawidth = 16;parameter addrwidth = 10;parameter mem_depth = (2**addrwidth)-1;

input clk, we;input [1:0] byteena;input [datawidth-1:0] din1, din2;input [addrwidth-1:0] addr1, addr2;output reg [datawidth-1:0] dout;

reg [datawidth-1:0] mem [0:mem_depth];

always @(posedge clk) beginif (we)if(byteena[0]) mem[addr1][7:0] = din1;if(byteena[1]) mem[addr2] [15:8] = din2;dout = mem[addr1];

endendmodule

VHDL/Verilog Differences

Initializing RAM in VerilogYou can use the $readmemh (hex) and $readmemb (binary) Verilog functions to initialize RAMsand ROMs. When an initialized RAM or ROM is inferred, the appropriate attributes on theassociated RAM/ROM instances in the netlist are set.

Page 264: PrecisionRTL Style

Precision Synthesis Style Guide, 2011a Update2264

MemoryOptimization Issues

November 2011

Optimization Issues

Initialization ValuesThe following lists describes how Precision maps the initialization values to attributes in theEDIF file for each supported technology:

• Xilinx Virtex block RAMs use the INIT_XX and INITP_XX attributes.

• Xilinx Distributed RAMs use the INIT attribute on the flop.

• Altera APEX LPM_RAMs use a hex file with the filename specified by the LPM_FILE

attribute.

• Altera Stratix ALTSYNCRAMs use a hex file with the filename specified by the LPM_FILE

attribute.

• Lattice devices supporting sysMEM EBRs have the attribute INIT_VAL_XX applied byPrecision Synthesis. The MEM_INIT_FILE attribute can also be used, as decribed in“Memory Initialization” section of “Designing with Lattice Devices” chapter, PrecisionSynthesis Reference Manual.

Attributes Relating to MemoryThe following attributes affect memory inferencing:

• block_ram (HDL only): Allows you to disable the mapping of a particular RAMinstance to block RAM in Xilinx technologies.

• block_rom (HDL only): Allows attempt to infer a ROM for the signal that has theattribute specified.

• ram_block (HDL only): Guides Precision to map an inferred RAM structure into thetarget technology’s block RAM resource. If the target technology doesn’t support blockRAM, then the structure will be mapped into distributed RAM or logic.

• ram_block_type (Altera only): Guides Precision to map an inferred RAM structureinto the target technology’s Block RAM resource type. If the target technology doesn’tsupport Block RAM, then the structure will be mapped into distributed RAM or logic.

• rom_block (HDL only): Guides Precision to map an inferred ROM structure andtransform it into the target technology’s block RAM resource. If the target technologydoesn’t support block RAM, then the structure will be mapped into distributed RAM orlogic.

Page 265: PrecisionRTL Style

MemoryMemory Coding Examples

Precision Synthesis Style Guide, 2011a Update2 265November 2011

Memory Coding ExamplesThe following table shows the VHDL and Verilog examples described in this section. The codefiles are available in the Precision Synthesis software tree in the following directory:

<precision_install_dir>/shared/examples/style_guide_hdl/Memory

Table 8-2. Memory Examples

Example Description

Synchronous RAMexample source file: ram_synch

RAM with synchronous data input, dataoutput and address lines.

RAM with Synchronous Inputexample source file: ram_synch_in

RAM with synchronous data input andasynchronous address lines and data output.

RAM with Synchronous Outputexample source file: ram_synch_out

RAM with synchronous data output andasynchronous address and data input.

RAM with Synchronous Addressexample source file: ram_synch_in

RAM with synchronous address lines andasynchronous data input and data output.

RAM with Synchronous Input/Outputexample source file: ram_synch_io

RAM with synchronous data input and dataoutput and asynchronous address lines

Asynchronous RAMexample source file: ram_asynch

RAM with asynchronous data input, dataoutput and address lines.

Synchronous I/O RAMexample source file: ramio_synch

RAM with synchronous address, data input,and data output lines.

I/O RAM with Synchronous Inputexample source file: ramio_synch_in

RAM with synchronous data input andasynchronous address and data output lines.

I/O RAM with Synchronous Outputexample source file: ramio_synch_out

RAM with synchronous data output andasynchronous address and data input lines.

I/O RAM with Synchronous Addressexample source file: ramio_synch_add

RAM with synchronous address andasynchronous data input and data output lines.

I/O RAM with Synchronous Input/Outputexample source file: ramio_synch_io

RAM with synchronous data input and dataoutput and asynchronous address line.

I/O Asynchronous RAMexample source file: ramio_asynch

RAM with asynchronous data input, dataoutput and address lines.

Dual Port RAMexample source file: ram_dualport

A 32 by 8 dual port RAM. There are separateread and write clocks as well as separate readand write addresses.

Resets for Memoryexample source files: ram_reset1.v andram_reset2.v

Precision supports 2 types of reset formemory; reset that clears the contents of thememory array, and reset that clears the outputregisters on read ports.

Page 266: PrecisionRTL Style

Precision Synthesis Style Guide, 2011a Update2266

MemoryMemory Coding Examples

November 2011

ROMexample source file: rom_sin

This is an example of read-only memory.

Synchronous ROMexample source file: rom_to_blockram

This is an example of synchronous read-onlymemory.

Table 8-2. Memory Examples

Example Description

Page 267: PrecisionRTL Style

MemorySynchronous RAM

Precision Synthesis Style Guide, 2011a Update2 267November 2011

Synchronous RAMRAM with synchronous data input, data output and address lines.

VHDL Verilog

LIBRARY IEEE;USE IEEE.std_logic_1164.ALL ;USE ieee.numeric_std.ALL;

ENTITY ram_synch IS GENERIC (d_width : NATURAL := 4 ; a_width : NATURAL := 4);

PORT (data_in :IN UNSIGNED(d_width-1 DOWNTO 0);

address :IN UNSIGNED(a_width-1 DOWNTO 0);

wr_en, inclock, outclock :IN STD_LOGIC;

dout :OUT UNSIGNED(d_width-1 DOWNTO 0) );

END ENTITY;

ARCHITECTURE infer OF ram_synch IS TYPE mem_type IS ARRAY (2**a_width DOWNTO 0)

OF UNSIGNED(d_width-1 DOWNTO 0); SIGNAL mem: mem_type ; SIGNAL address_save :

UNSIGNED(a_width-1 DOWNTO 0);

BEGIN

ram : PROCESS (inclock,outclock) BEGIN

IF (inclock = ‘1’ AND inclock’EVENT) THEN IF (wr_en = ‘1’) THEN mem(TO_INTEGER(address_save)) <= data_in; END IF ; address_save <= address; END IF;

IF (outclock = ‘1’ AND outclock’EVENT) THEN dout <= mem(TO_INTEGER(address_save)); END IF;

END PROCESS ram;

END ARCHITECTURE ;

module ram_synch (data_in, address, wr_en, inclock, outclock, dout);

parameter d_width = 4; parameter a_width = 4;

input [d_width-1:0] data_in; input [a_width-1:0] address; input wr_en, inclock,

outclock;

output [d_width-1:0] dout;

reg [d_width-1:0] dout; reg [d_width-1:0] mem

[1<<a_width:0]; reg [a_width-1:0]

address_save;

always @(posedge inclock) begin if (wr_en)

mem[address_save] <=data_in;

address_save <= address; end

always @(posedge outclock) dout <=

mem[address_save];

endmodule

Page 268: PrecisionRTL Style

Precision Synthesis Style Guide, 2011a Update2268

MemoryRAM with Synchronous Input

November 2011

RAM with Synchronous InputRAM with synchronous data input and asynchronous address lines and data output.

VHDL Verilog

LIBRARY IEEE;USE IEEE.std_logic_1164.ALL ;USE ieee.numeric_std.ALL;

ENTITY ram_synch_in IS GENERIC (d_width : NATURAL := 4 ; a_width : NATURAL := 8);

PORT (data_in :IN UNSIGNED(d_width-1 DOWNTO 0);

address :IN UNSIGNED(a_width-1 DOWNTO 0);

wr_en, inclock : IN STD_LOGIC ; dout :

OUT UNSIGNED(d_width-1 DOWNTO 0));END ENTITY ;

ARCHITECTURE infer OF ram_synch_in IS TYPE mem_type IS ARRAY (2**a_width DOWNTO 0) OF UNSIGNED(d_width - 1 DOWNTO 0); SIGNAL mem: mem_type ;

BEGIN

ram : PROCESS (inclock) BEGIN IF (inclock = ‘1’ AND inclock’EVENT) THEN IF (wr_en = ‘1’) THEN mem(TO_INTEGER(address)) <= data_in ; END IF ; END IF; END PROCESS ram;

dout <= mem(TO_INTEGER(address));END ARCHITECTURE ;

module ram_synch_in (data_in, address, wr_en, inclock, dout);

parameter d_width = 4; parameter a_width = 8;

input [d_width-1:0] data_in; input [a_width-1:0] address; input wr_en, inclock;

output [d_width-1:0] dout;

reg [d_width-1:0] mem[1<<a_width:0];

always @(posedge inclock) begin if (wr_en)

mem[address] <= data_in; end

assign dout = mem[address];endmodule

Page 269: PrecisionRTL Style

MemoryRAM with Synchronous Output

Precision Synthesis Style Guide, 2011a Update2 269November 2011

RAM with Synchronous OutputRAM with synchronous data output and asynchronous address and data input.

VHDL Verilog

LIBRARY IEEE;USE IEEE.std_logic_1164.ALL ;USE ieee.numeric_std.ALL;

ENTITY ram_synch_out IS GENERIC (d_width : NATURAL := 4; a_width : NATURAL := 4);

PORT (data_in : IN UNSIGNED(d_width-1 DOWNTO0);

address : IN UNSIGNED(a_width-1 DOWNTO0);

wr_en, outclock : IN STD_LOGIC; dout : OUT UNSIGNED(d_width-1 DOWNTO

0));END ENTITY;

ARCHITECTURE infer OF ram_synch_out IS TYPE mem_type IS ARRAY (2**a_width DOWNTO 0)

OFUNSIGNED(d_width-1 DOWNTO

0); SIGNAL mem: mem_type ;

BEGIN

ram: PROCESS (address,data_in,wr_en,outclock) BEGIN IF (wr_en = ’1’) THEN mem(TO_INTEGER(address)) <= data_in ; END IF ;

IF (outclock = ’1’ AND outclock’EVENT) THEN dout <= mem(TO_INTEGER(address)); END IF; END PROCESS ram;

END ARCHITECTURE ;

module ram_synch_out (data_in, address, wr_en, outclock, dout);

parameter d_width = 4; parameter a_width = 4;

input [d_width-1:0] data_in; input [a_width-1:0] address; input wr_en, outclock;

output [d_width-1:0] dout;

reg [d_width-1:0] dout; reg [d_width-1:0] mem

[1<<a_width:0];

always @(address or data_in or wr_en or outclock) if (wr_en) mem[address] <= data_in;

always @(posedge outclock) dout <= mem[address];

endmodule

Page 270: PrecisionRTL Style

Precision Synthesis Style Guide, 2011a Update2270

MemoryRAM with Synchronous Address

November 2011

RAM with Synchronous AddressRAM with synchronous address lines and asynchronous data input and data output.

VHDL Verilog

LIBRARY IEEE;USE IEEE.std_logic_1164.ALL ;USE ieee.numeric_std.ALL;

ENTITY ram_synch_add IS GENERIC (d_width : NATURAL := 4 ; a_width : NATURAL := 4);

PORT (data_in : IN UNSIGNED(d_width-1 DOWNTO0);

address : IN UNSIGNED(a_width-1 DOWNTO0);

wr_en, addr_clk : IN STD_LOGIC; dout : OUT UNSIGNED(d_width-1 DOWNTO

0));END ENTITY;

ARCHITECTURE infer OF ram_synch_add IS TYPE mem_type IS ARRAY (2**a_width DOWNTO 0)

OFUNSIGNED(d_width-1 DOWNTO

0) ; SIGNAL mem: mem_type ; SIGNAL address_save : UNSIGNED(a_width-1

DOWNTO 0) ;

BEGIN

ram : PROCESS (wr_en, data_in, address, addr_clk) BEGIN IF (wr_en = ’1’) THEN mem(TO_INTEGER(address_save)) <= data_in; END IF ;

IF (addr_clk’EVENT AND addr_clk = ’1’) THEN address_save <= address; END IF; END PROCESS ram;

dout <= mem(TO_INTEGER(address_save));END ARCHITECTURE ;

module ram_synch_addr (data_in, address, wr_en, addr_clock, dout);

parameter d_width = 4; parameter a_width = 4;

input [d_width-1:0] data_in; input [a_width-1:0] address; input wr_en, addr_clock;

output [d_width-1:0] dout;

reg [d_width-1:0] mem[1<<a_width:0];

reg [a_width-1:0] address_save;

always @(wr_en or data_in oraddress)

if (wr_en) mem[address_save] =

data_in;

always @(posedge addr_clock) address_save <= address;

assign dout = mem[address_save];

endmodule

Page 271: PrecisionRTL Style

MemoryRAM with Synchronous Input/Output

Precision Synthesis Style Guide, 2011a Update2 271November 2011

RAM with Synchronous Input/OutputRAM with synchronous data input and data output and asynchronous address lines

VHDL Verilog

LIBRARY IEEE;USE IEEE.std_logic_1164.ALL ;USE ieee.numeric_std.ALL;

ENTITY ram_synch_io IS GENERIC (d_width : NATURAL := 4; a_width : NATURAL := 4);

PORT (data_in : IN UNSIGNED(d_width-1 DOWNTO 0); address : IN UNSIGNED(a_width-1 DOWNTO 0); wr_en, inclock, outclock : IN STD_LOGIC ; dout : OUT UNSIGNED(d_width-1 DOWNTO 0));END ENTITY;

ARCHITECTURE infer OF ram_synch_io IS TYPE mem_type IS ARRAY (2**a_width DOWNTO 0) OF UNSIGNED(d_width-1 DOWNTO 0); SIGNAL mem: mem_type ;

BEGIN

ram : PROCESS (inclock,outclock) BEGIN

IF (inclock = ’1’ AND inclock’EVENT) THEN IF (wr_en = ’1’) THEN mem(TO_INTEGER(address)) <= data_in ; END IF ; END IF;

IF (outclock = ’1’ AND outclock’EVENT) THEN dout <= mem(TO_INTEGER(address)); END IF;

END PROCESS ram;

END ARCHITECTURE ;

module ram_synch_io (data_in, address, wr_en, inclock, outclock, dout);

parameter d_width = 4; parameter a_width = 4;

input [d_width-1:0] data_in; input [a_width-1:0] address;

input wr_en, inclock, outclock;

output [d_width-1:0] dout;

reg [d_width-1:0] dout; reg [d_width-1:0] mem

[1<<a_width:0];

always @(posedge inclock) if (wr_en) mem[address] <=

data_in;

always @(posedge outclock) dout <= mem[address];

endmodule

Page 272: PrecisionRTL Style

Precision Synthesis Style Guide, 2011a Update2272

MemoryAsynchronous RAM

November 2011

Asynchronous RAMRAM with asynchronous data input, data output and address lines.

VHDL Verilog

LIBRARY IEEE;USE IEEE.std_logic_1164.ALL;USE ieee.numeric_std.ALL;

ENTITY ram_asynch IS GENERIC (d_width : NATURAL := 4; a_width : NATURAL := 4);

PORT (data_in : IN UNSIGNED(d_width-1 DOWNTO0);

address : IN UNSIGNED(a_width-1 DOWNTO0);

wr_en : IN STD_LOGIC; dout : OUT UNSIGNED(d_width-1 DOWNTO

0));END ENTITY ;

ARCHITECTURE infer OF ram_asynch ISTYPE mem_type IS ARRAY (2**a_width DOWNTO 0) OF

UNSIGNED(d_width-1 DOWNTO0);

SIGNAL mem: mem_type ;

BEGIN

asynch : PROCESS (wr_en,address,data_in)BEGIN IF (wr_en = ’1’) THEN mem(TO_INTEGER(address)) <= data_in; END IF ;END PROCESS ;

dout <= mem(TO_INTEGER(address));END ARCHITECTURE ;

module ram_asynch (data_in, address, wr_en, dout);

parameter d_width = 4; parameter a_width = 4;

input [d_width-1:0] data_in; input [a_width-1:0] address; input wr_en;

output [d_width-1:0] dout;

reg [d_width-1:0] dout; reg [d_width-1:0] mem

[1<<a_width:0];

always @(wr_en or address ordata_in)

begin if (wr_en) mem[address] <= data_in; dout <= mem[address]; endendmodule

Page 273: PrecisionRTL Style

MemorySynchronous I/O RAM

Precision Synthesis Style Guide, 2011a Update2 273November 2011

Synchronous I/O RAMRAM with synchronous address, data input, and data output lines.

VHDL Verilog

LIBRARY IEEE;USE IEEE.std_logic_1164.ALL ;USE ieee.numeric_std.ALL;

ENTITY ramio_synch IS GENERIC (d_width : NATURAL := 4 ; a_width : NATURAL := 4); PORT (data : INOUT UNSIGNED(d_width-1 DOWNTO 0); address : IN UNSIGNED(a_width-1 DOWNTO 0); wr_en, read_en, inclock, outclock : IN STD_LOGIC);END ENTITY;

ARCHITECTURE infer OF ramio_synch IS TYPE mem_type IS ARRAY (2**a_width DOWNTO 0) OF UNSIGNED(d_width-1 DOWNTO 0); SIGNAL mem: mem_type ; SIGNAL data_tmp : UNSIGNED(d_width-1 DOWNTO 0); SIGNAL address_save : UNSIGNED(a_width-1 DOWNTO 0); BEGIN sync_in : PROCESS (inclock,outclock) BEGIN IF (inclock = ‘1’ AND inclock’EVENT) THEN IF (wr_en = ‘1’) THEN mem(TO_INTEGER(address)) <= data ; END IF ; address_save <= address; END IF;

IF (outclock = ‘1’ AND outclock’EVENT) THEN data_tmp <= mem(TO_INTEGER(address_save)); END IF; END PROCESS sync_in;data <= data_tmp WHEN (read_en = ‘1’) ELSE (OTHERS =>

‘Z’);END ARCHITECTURE ;

module ramio_synch (data, address, wr_en, read_en, inclock, outclock);

parameter d_width = 4; parameter a_width = 4;

input [a_width-1:0] address;input wr_en, read_en, inclock,

outclock;

inout [d_width-1:0] data;

reg [d_width-1:0] mem[1<<a_width:0];

reg [d_width-1:0] data_tmp;reg [a_width-1:0] address_save;

always @(posedge inclock) begin if (wr_en) mem[address] <= data; address_save <= address; end

always @(posedge outclock) data_tmp <=

mem[address_save];

assign data = read_en ?data_tmp : ‘bz;

endmodule

Page 274: PrecisionRTL Style

Precision Synthesis Style Guide, 2011a Update2274

MemoryI/O RAM with Synchronous Input

November 2011

I/O RAM with Synchronous InputRAM with synchronous data input and asynchronous address and data output lines.

VHDL Verilog

LIBRARY IEEE;USE IEEE.std_logic_1164.ALL ;USE ieee.numeric_std.ALL;

ENTITY ramio_synch_in IS GENERIC (d_width : NATURAL := 4 ; a_width : NATURAL := 4);

PORT (data : INOUT UNSIGNED(d_width-1 DOWNTO 0); address : IN UNSIGNED(a_width-1 DOWNTO 0);

wr_en, read_en, inclock : IN STD_LOGIC );END ENTITY;

ARCHITECTURE infer OF ramio_synch_in IS TYPE mem_type IS ARRAY (2**a_width DOWNTO 0) OF

UNSIGNED(d_width-1 DOWNTO 0); SIGNAL mem: mem_type ;

BEGIN

sync_in : PROCESS (inclock) BEGIN

IF (inclock = ‘1’ AND inclock’EVENT) THEN IF (wr_en = ‘1’) THEN mem(TO_INTEGER(address)) <= data ; END IF ; END IF;

END PROCESS sync_in;

data <= mem(TO_INTEGER(address)) WHEN (read_en = ‘1’) ELSE (OTHERS => ‘Z’);

END ARCHITECTURE ;

module ramio_synch_in (data,address,

wr_en,read_en,inclock);

parameter d_width = 4; parameter a_width = 4;

input [a_width-1:0] address; input wr_en, read_en,

inclock; inout [d_width-1:0] data;

reg [d_width-1:0] mem[1<<a_width:0];

always @(posedge inclock) if (wr_en) mem[address] <=

data;

assign data =read_en?mem[address]:’bz;

endmodule

Page 275: PrecisionRTL Style

MemoryI/O RAM with Synchronous Output

Precision Synthesis Style Guide, 2011a Update2 275November 2011

I/O RAM with Synchronous OutputRAM with synchronous data output and asynchronous address and data input lines.

VHDL Verilog

LIBRARY IEEE;USE IEEE.std_logic_1164.ALL ;USE ieee.numeric_std.ALL;

ENTITY ramio_synch_out IS GENERIC (d_width : NATURAL := 4; a_width : NATURAL := 4);

PORT (data : INOUT UNSIGNED (d_width-1 DOWNTO 0); address : IN UNSIGNED (a_width-1 DOWNTO 0); wr_en, read_en, outclock : IN STD_LOGIC);END ENTITY;

ARCHITECTURE infer OF ramio_synch_out IS TYPE mem_type IS ARRAY (2**a_width DOWNTO 0)

OF UNSIGNED(d_width-1 DOWNTO 0); SIGNAL mem: mem_type ; SIGNAL data_tmp : UNSIGNED(d_width-1 DOWNTO 0);

BEGIN

sync_in : PROCESS (wr_en,address, data,outclock) BEGIN

IF (wr_en = ‘1’) THEN mem(TO_INTEGER(address)) <= data ; END IF ;

IF (outclock=’1’ AND outclock’EVENT) THEN data_tmp <= mem(TO_INTEGER(address)); END IF;

END PROCESS sync_in;

data <= data_tmp WHEN (read_en = ‘1’) ELSE (OTHERS => ‘Z’);

END ARCHITECTURE ;

module ramio_synch_out (data, address, wr_en, read_en,

outclock); parameter d_width = 4; parameter a_width = 4;

input [a_width-1:0] address; input wr_en, read_en,

outclock; inout [d_width-1:0] data;

reg [d_width-1:0] mem[1<<a_width:0];

reg [d_width-1:0] data_tmp;

always @(wr_en or address ordata)

if (wr_en) mem[address] <= data;

always @(posedge outclock) data_tmp <= mem[address];

assign data = read_en ?data_tmp:’bz;

endmodule

Page 276: PrecisionRTL Style

Precision Synthesis Style Guide, 2011a Update2276

MemoryI/O RAM with Synchronous Address

November 2011

I/O RAM with Synchronous AddressRAM with synchronous address and asynchronous data input and data output lines.

VHDL Verilog

LIBRARY IEEE;USE IEEE.std_logic_1164.ALL ;USE ieee.numeric_std.ALL;

ENTITY ramio_synch_add IS GENERIC (d_width : NATURAL := 4 ; a_width : NATURAL := 4);

PORT (data : INOUT UNSIGNED(d_width-1 DOWNTO 0); address : IN UNSIGNED(a_width-1 DOWNTO 0);

wr_en, read_en, addr_clock : IN STD_LOGIC);END ENTITY;

ARCHITECTURE infer OF ramio_synch_add IS TYPE mem_type IS ARRAY (2**a_width DOWNTO 0) OF UNSIGNED(d_width-1 DOWNTO 0);

SIGNAL mem: mem_type ; SIGNAL address_save : UNSIGNED(a_width-1 DOWNTO

0);

BEGIN

ram : PROCESS (address, addr_clock, wr_en, data) BEGIN

IF (wr_en = ‘1’) THEN mem(TO_INTEGER(address)) <= data ; END IF ;

IF (addr_clock = ‘1’ AND addr_clock’EVENT) THEN address_save <= address; END IF;

END PROCESS ram;

data <= mem(TO_INTEGER(address_save)) WHEN (read_en = ‘1’) ELSE (OTHERS => ‘Z’);

END ARCHITECTURE ;

module ramio_synch_add (data,address,

wr_en,read_en,

addr_clock); parameter d_width = 4; parameter a_width = 4;

input [a_width-1:0] address; input wr_en, read_en, addr_clock; inout [d_width-1:0] data;

reg [d_width-1:0] mem[1<<a_width:0];

reg [a_width-1:0] add_save;

always @(posedge addr_clock) add_save <= address;

always @(address or wr_en or

data) if (wr_en) mem[address] <= data;

assign data = read_en ? mem

[add_save]:’bz;

endmodule

Page 277: PrecisionRTL Style

MemoryI/O RAM with Synchronous Input/Output

Precision Synthesis Style Guide, 2011a Update2 277November 2011

I/O RAM with Synchronous Input/OutputRAM with synchronous data input and data output and asynchronous address line.

VHDL Verilog

LIBRARY IEEE;USE IEEE.std_logic_1164.ALL ;USE ieee.numeric_std.ALL;

ENTITY ramio_synch_io IS GENERIC (d_width : NATURAL := 4 ; a_width : NATURAL := 4);

PORT (data : INOUT UNSIGNED(d_width-1 DOWNTO 0); address : IN UNSIGNED(a_width-1 DOWNTO 0); wr_en, read_en, inclock, outclock : IN STD_LOGIC );END ENTITY;

ARCHITECTURE infer OF ramio_synch_io IS TYPE mem_type IS ARRAY (2**a_width DOWNTO 0) OF UNSIGNED (d_width-1 DOWNTO 0); SIGNAL mem: mem_type ; SIGNAL data_tmp : UNSIGNED (d_width-1 DOWNTO 0);

BEGIN

sync_in : PROCESS (inclock,outclock) BEGIN

IF (inclock = ‘1’ AND inclock’EVENT) THEN IF (wr_en = ‘1’) THEN mem(TO_INTEGER(address)) <= data ; END IF ; END IF;

IF (outclock = ‘1’ AND outclock’EVENT) THEN data_tmp <= mem(TO_INTEGER(address)); END IF;

END PROCESS sync_in;

data <= data_tmp WHEN (read_en = ‘1’) ELSE (OTHERS => ‘Z’);

END ARCHITECTURE ;

module ramio_synch_io (data, address, wr_en, read_en, inclock, outclock); parameter d_width = 4; parameter a_width = 4;

input [a_width-1:0] address; input wr_en, read_en, inclock, outclock;

inout [d_width-1:0] data;

reg [d_width-1:0] mem [1<<a_width:0]; reg [d_width-1:0] data_tmp;

always @(posedge inclock) if (wr_en) mem[address] <= data;

always @(posedge outclock) data_tmp <= mem[address];

assign data = read_en ? data_tmp : ‘bz;endmodule

Page 278: PrecisionRTL Style

Precision Synthesis Style Guide, 2011a Update2278

MemoryI/O Asynchronous RAM

November 2011

I/O Asynchronous RAMRAM with asynchronous data input, data output and address lines.

VHDL Verilog

LIBRARY IEEE;USE IEEE.std_logic_1164.ALL ;USE ieee.numeric_std.ALL;

ENTITY ramio_asynch IS GENERIC (d_width : NATURAL := 4 ; a_width : NATURAL := 4);

PORT (data : INOUT UNSIGNED(d_width-1 DOWNTO 0); address : IN UNSIGNED(a_width-1 DOWNTO 0); wr_en, read_en : IN STD_LOGIC) ;END ENTITY ;

ARCHITECTURE infer OF ramio_asynch IS TYPE mem_type IS ARRAY (2**a_width DOWNTO 0) OF UNSIGNED(d_width - 1 DOWNTO 0); SIGNAL mem: mem_type ;

BEGIN

asynch : PROCESS (wr_en,address,data)BEGIN IF (wr_en = ‘1’) THEN mem(TO_INTEGER(address)) <= data ; END IF ;END PROCESS ;

data <= mem(TO_INTEGER(address)) WHEN (read_en = ‘1’) ELSE (OTHERS => ‘Z’);END ARCHITECTURE ;

module ramio_asynch (data, address, wr_en, read_en);

parameter d_width = 4; parameter a_width = 4;

input [a_width-1:0] address; input wr_en, read_en; inout [d_width-1:0] data;

reg [d_width-1:0] mem[1<<a_width:0];

always @(wr_en or address or data)

if (wr_en) mem[address] <= data;

assign data = read_en ? mem [address]:’bz;

endmodule

Page 279: PrecisionRTL Style

MemoryDual Port RAM

Precision Synthesis Style Guide, 2011a Update2 279November 2011

Dual Port RAMA 32 by 8 dual port RAM. There are separate read and write clocks as well as separate read andwrite addresses.

VHDL Verilog

LIBRARY ieee;USE ieee.std_logic_1164.ALL;USE ieee.numeric_std.ALL;

ENTITY ram_dualport IS PORT (write_clk, wea : IN STD_LOGIC; rd_clk : IN STD_LOGIC; data_in : IN UNSIGNED(7 DOWNTO 0); addr_write, addr_read : IN UNSIGNED (4 DOWNTO 0);

data_out : OUT UNSIGNED(7 DOWNTO 0));END ENTITY;

ARCHITECTURE infer OF ram_dualport ISTYPE mem_type IS ARRAY (31 DOWNTO 0) OF UNSIGNED(7 DOWNTO 0);SIGNAL MEM : mem_type;BEGIN

ram_proc: PROCESS (write_clk, rd_clk)BEGIN IF (write_clk’EVENT AND write_clk=’1’) THEN IF wea=’1’ THEN MEM(TO_INTEGER(addr_write)) <= data_in; END IF; END IF;

IF ( rd_clk’EVENT AND rd_clk=’1’ ) THEN data_out <= MEM(TO_INTEGER(addr_read)); END IF;END PROCESS ram_proc;END ARCHITECTURE;

module ram_dualport (write_clock, wea, read_clock, data_in, addr_write, addr_read, data_out);

input write_clock, wea, read_clock;

input [7:0] data_in; input [4:0] addr_write, addr_read;

output [7:0] data_out;

reg [7:0] data_out; reg [7:0] mem [31:0];

always @(posedge write_clock) if (wea) mem[addr_write] <= data_in;

always @(posedge read_clock) data_out <= mem [addr_read];endmodule

Page 280: PrecisionRTL Style

Precision Synthesis Style Guide, 2011a Update2280

MemoryResets for Memory

November 2011

Resets for MemoryPrecision supports 2 types of reset for memory; reset that clears the contents of the memoryarray, and reset that clears the output registers on read ports.

The Verilog source files shown below are named ram_reset1.v and ram_reset1.v, arelocated in the examples directory, as noted in “Memory Coding Examples” on page 265

Verilog — reset memory contents Verilog — reset read port registers

‘define WIDTH_A 9‘define WIDTH_D 4‘define RAM_DEPTH 256

module top ( addr, we, clk, din, dout, rst );input [‘WIDTH_A-1:0] addr;input we, rst;input clk;input [‘WIDTH_D-1:0] din;output [‘WIDTH_D-1:0] dout;reg [‘WIDTH_D-1:0] mem[0:‘RAM_DEPTH-1];reg [‘WIDTH_D-1:0] dout;

reg [‘WIDTH_A:0] i;

always @( posedge clk or posedge rst )begin if( rst) begin for (i = 0 ; i <= 255; i = i+1) mem[i] <= 0; end else begin if( we ) mem[addr] <= din; dout <= mem[addr]; endendendmodule

‘define WIDTH_A 8‘define WIDTH_D 4‘define RAM_DEPTH 256

module top ( addr, we, clk, din, dout, rst ); input [‘WIDTH_A-1:0] addr; input we, rst; input clk; input [‘WIDTH_D-1:0] din; output [‘WIDTH_D-1:0] dout; reg [‘WIDTH_D-1:0] mem[0:‘RAM_DEPTH-1]; reg [‘WIDTH_D-1:0] dout;

always @( posedge clk ) begin

if( we ) mem[addr] <= din;

if( rst) dout <= 0; else dout <= mem[addr]; end

endmodule

Page 281: PrecisionRTL Style

MemoryROM

Precision Synthesis Style Guide, 2011a Update2 281November 2011

ROMThis is an example of read-only memory.

VHDL

The HDL source file shown below is named rom_sin.vhd and is located in the examplesdirectory, as noted in “Memory Coding Examples” on page 265.

LIBRARY IEEE;USE IEEE.STD_LOGIC_1164.ALL;USE ieee.numeric_std.ALL;

ENTITY rom_sin IS PORT (addr: IN UNSIGNED(6 DOWNTO 0); sin: OUT UNSIGNED(10 DOWNTO 0)); attribute rom_block : boolean; attribute rom_block of sin : signal is TRUE;END ENTITY;

ARCHITECTURE rtl OF rom_sin ISBEGINlut: PROCESS (addr)BEGIN CASE addr IS WHEN “0000000” => sin <= “00000000110”; WHEN “0000001” => sin <= “00000001100”; WHEN “0000010” => sin <= “00000010011”; WHEN “0000011” => sin <= “00000011001”; WHEN “0000100” => sin <= “00000100000”; WHEN “0000101” => sin <= “00000100110”; WHEN “0000110” => sin <= “00000101101”; WHEN “0000111” => sin <= “00000110011”; WHEN “0001000” => sin <= “00000111001”; WHEN “0001001” => sin <= “00001000000”; WHEN “0001010” => sin <= “00001000110”; WHEN “0001011” => sin <= “00001001101”; WHEN “0001100” => sin <= “00001010011”; WHEN “0001101” => sin <= “00001011010”; WHEN “0001110” => sin <= “00001100000”; WHEN “0001111” => sin <= “00001100110”; WHEN “0010000” => sin <= “00001101101”; WHEN “0010001” => sin <= “00001110011”; WHEN “0010010” => sin <= “00001111010”; WHEN “0010011” => sin <= “00010000000”; WHEN “0010100” => sin <= “00010000111”; WHEN “0010101” => sin <= “00010001101”; WHEN “0010110” => sin <= “00010010011”; WHEN “0010111” => sin <= “00010011010”; WHEN “0011000” => sin <= “00010100000”; WHEN “0011001” => sin <= “00010100111”; WHEN “0011010” => sin <= “00010101101”; WHEN “0011011” => sin <= “00010110011”; WHEN “0011100” => sin <= “00010111010”; WHEN “0011101” => sin <= “00011000000”; WHEN “0011110” => sin <= “00011000111”; WHEN “0011111” => sin <= “00011001101”;

Page 282: PrecisionRTL Style

Precision Synthesis Style Guide, 2011a Update2282

MemoryROM

November 2011

WHEN “0100000” => sin <= “00011010011”; WHEN “0100001” => sin <= “00011011010”; WHEN “0100010” => sin <= “00011100000”; WHEN “0100011” => sin <= “00011100111”; WHEN “0100100” => sin <= “00011101101”; WHEN “0100101” => sin <= “00011110011”; WHEN “0100110” => sin <= “00011111010”; WHEN “0100111” => sin <= “00100000000”; WHEN “0101000” => sin <= “00100000111”; WHEN “0101001” => sin <= “00100001101”; WHEN “0101010” => sin <= “00100010011”; WHEN “0101011” => sin <= “00100011010”; WHEN “0101100” => sin <= “00100100000”; WHEN “0101101” => sin <= “00100100110”; WHEN “0101110” => sin <= “00100101101”; WHEN “0101111” => sin <= “00100110011”; WHEN “0110000” => sin <= “00100111010”; WHEN “0110001” => sin <= “00101000000”; WHEN “0110010” => sin <= “00101000110”; WHEN “0110011” => sin <= “00101001101”; WHEN “0110100” => sin <= “00101010011”; WHEN “0110101” => sin <= “00101011001”; WHEN “0110110” => sin <= “00101100000”; WHEN “0110111” => sin <= “00101100110”; WHEN “0111000” => sin <= “00101101100”; WHEN “0111001” => sin <= “00101110011”; WHEN “0111010” => sin <= “00101111001”; WHEN “0111011” => sin <= “00101111111”; WHEN “0111100” => sin <= “00110000110”; WHEN “0111101” => sin <= “00110001100”; WHEN “0111110” => sin <= “00110010010”; WHEN “0111111” => sin <= “00110011001”; WHEN “1000000” => sin <= “00110011111”; WHEN “1000001” => sin <= “00110100101”; WHEN “1000010” => sin <= “00110101011”; WHEN “1000011” => sin <= “00110110010”; WHEN “1000100” => sin <= “00110111000”; WHEN “1000101” => sin <= “00110111110”; WHEN “1000110” => sin <= “00111000101”; WHEN “1000111” => sin <= “00111001011”; WHEN “1001000” => sin <= “00111010001”; WHEN “1001001” => sin <= “00111010111”; WHEN “1001010” => sin <= “00111011110”; WHEN “1001011” => sin <= “00111100100”; WHEN “1001100” => sin <= “00111101010”; WHEN “1001101” => sin <= “00111110000”; WHEN “1001110” => sin <= “00111110111”; WHEN “1001111” => sin <= “00111111101”; WHEN “1010000” => sin <= “01000000011”; WHEN “1010001” => sin <= “01000001001”; WHEN “1010010” => sin <= “01000001111”; WHEN “1010011” => sin <= “01000010110”; WHEN “1010100” => sin <= “01000011100”; WHEN “1010101” => sin <= “01000100010”; WHEN “1010110” => sin <= “01000101000”; WHEN “1010111” => sin <= “01000101111”; WHEN “1011000” => sin <= “01000110101”; WHEN “1011001” => sin <= “01000111011”;

Page 283: PrecisionRTL Style

MemoryROM

Precision Synthesis Style Guide, 2011a Update2 283November 2011

WHEN “1011010” => sin <= “01001000001”; WHEN “1011011” => sin <= “01001000111”; WHEN “1011100” => sin <= “01001001101”; WHEN “1011101” => sin <= “01001010100”; WHEN “1011110” => sin <= “01001011010”; WHEN “1011111” => sin <= “01001100000”; WHEN “1100000” => sin <= “01001100110”; WHEN “1100001” => sin <= “01001101100”; WHEN “1100010” => sin <= “01001110010”; WHEN “1100011” => sin <= “01001111000”; WHEN “1100100” => sin <= “01001111110”; WHEN “1100101” => sin <= “01010000101”; WHEN “1100110” => sin <= “01010001011”; WHEN “1100111” => sin <= “01010010001”; WHEN “1101000” => sin <= “01010010111”; WHEN “1101001” => sin <= “01010011101”; WHEN “1101010” => sin <= “01010100011”; WHEN “1101011” => sin <= “01010101001”; WHEN “1101100” => sin <= “01010101111”; WHEN “1101101” => sin <= “01010110101”; WHEN “1101110” => sin <= “01010111011”; WHEN “1101111” => sin <= “01011000001”; WHEN “1110000” => sin <= “01011000111”; WHEN “1110001” => sin <= “01011001101”; WHEN “1110010” => sin <= “01011010011”; WHEN “1110011” => sin <= “01011011001”; WHEN “1110100” => sin <= “01011011111”; WHEN “1110101” => sin <= “01011100101”; WHEN “1110110” => sin <= “01011101011”; WHEN “1110111” => sin <= “01011110001”; WHEN “1111000” => sin <= “01011110111”; WHEN “1111001” => sin <= “01011111101”; WHEN “1111010” => sin <= “01100000011”; WHEN “1111011” => sin <= “01100001001”; WHEN “1111100” => sin <= “01100001111”; WHEN “1111101” => sin <= “01100010101”; WHEN “1111111” => sin <= “01100100001”; WHEN OTHERS => sin <= “00000000000”; END CASE;END PROCESS lut;

END ARCHITECTURE;

Page 284: PrecisionRTL Style

Precision Synthesis Style Guide, 2011a Update2284

MemoryROM

November 2011

Verilog

The HDL source file shown below is named rom_sin.v and is located in the examplesdirectory, as noted in “Memory Coding Examples” on page 265.

module rom_sin (addr, sin); input [6:0] addr; output [10:0] sin;

reg [10:0] sin;//pragma attribute sin rom_block 1

always@(addr) case (addr) 0000000 : sin = 00000000110; 0000001 : sin = 00000001100; 0000010 : sin = 00000010011; 0000011 : sin = 00000011001; 0000100 : sin = 00000100000; 0000101 : sin = 00000100110; 0000110 : sin = 00000101101; 0000111 : sin = 00000110011; 0001000 : sin = 00000111001; 0001001 : sin = 00001000000; 0001010 : sin = 00001000110; 0001011 : sin = 00001001101; 0001100 : sin = 00001010011; 0001101 : sin = 00001011010; 0001110 : sin = 00001100000; 0001111 : sin = 00001100110; 0010000 : sin = 00001101101; 0010001 : sin = 00001110011; 0010010 : sin = 00001111010; 0010011 : sin = 00010000000; 0010100 : sin = 00010000111; 0010101 : sin = 00010001101; 0010110 : sin = 00010010011; 0010111 : sin = 00010011010; 0011000 : sin = 00010100000; 0011001 : sin = 00010100111; 0011010 : sin = 00010101101; 0011011 : sin = 00010110011; 0011100 : sin = 00010111010; 0011101 : sin = 00011000000; 0011110 : sin = 00011000111; 0011111 : sin = 00011001101; 0100000 : sin = 00011010011; 0100001 : sin = 00011011010; 0100010 : sin = 00011100000; 0100011 : sin = 00011100111; 0100100 : sin = 00011101101; 0100101 : sin = 00011110011; 0100110 : sin = 00011111010; 0100111 : sin = 00100000000; 0101000 : sin = 00100000111; 0101001 : sin = 00100001101; 0101010 : sin = 00100010011; 0101011 : sin = 00100011010;

Page 285: PrecisionRTL Style

MemoryROM

Precision Synthesis Style Guide, 2011a Update2 285November 2011

0101100 : sin = 00100100000; 0101101 : sin = 00100100110; 0101110 : sin = 00100101101; 0101111 : sin = 00100110011; 0110000 : sin = 00100111010; 0110001 : sin = 00101000000; 0110010 : sin = 00101000110; 0110011 : sin = 00101001101; 0110100 : sin = 00101010011; 0110101 : sin = 00101011001; 0110110 : sin = 00101100000; 0110111 : sin = 00101100110; 0111000 : sin = 00101101100; 0111001 : sin = 00101110011; 0111010 : sin = 00101111001; 0111011 : sin = 00101111111; 0111100 : sin = 00110000110; 0111101 : sin = 00110001100; 0111110 : sin = 00110010010; 0111111 : sin = 00110011001; 1000000 : sin = 00110011111; 1000001 : sin = 00110100101; 1000010 : sin = 00110101011; 1000011 : sin = 00110110010; 1000100 : sin = 00110111000; 1000101 : sin = 00110111110; 1000110 : sin = 00111000101; 1000111 : sin = 00111001011; 1001000 : sin = 00111010001; 1001001 : sin = 00111010111; 1001010 : sin = 00111011110; 1001011 : sin = 00111100100; 1001100 : sin = 00111101010; 1001101 : sin = 00111110000; 1001110 : sin = 00111110111; 1001111 : sin = 00111111101; 1010000 : sin = 01000000011; 1010001 : sin = 01000001001; 1010010 : sin = 01000001111; 1010011 : sin = 01000010110; 1010100 : sin = 01000011100; 1010101 : sin = 01000100010; 1010110 : sin = 01000101000; 1010111 : sin = 01000101111; 1011000 : sin = 01000110101; 1011001 : sin = 01000111011; 1011010 : sin = 01001000001; 1011011 : sin = 01001000111; 1011100 : sin = 01001001101; 1011101 : sin = 01001010100; 1011110 : sin = 01001011010; 1011111 : sin = 01001100000; 1100000 : sin = 01001100110; 1100001 : sin = 01001101100; 1100010 : sin = 01001110010; 1100011 : sin = 01001111000; 1100100 : sin = 01001111110; 1100101 : sin = 01010000101;

Page 286: PrecisionRTL Style

Precision Synthesis Style Guide, 2011a Update2286

MemoryROM

November 2011

1100110 : sin = 01010001011; 1100111 : sin = 01010010001; 1101000 : sin = 01010010111; 1101001 : sin = 01010011101; 1101010 : sin = 01010100011; 1101011 : sin = 01010101001; 1101100 : sin = 01010101111; 1101101 : sin = 01010110101; 1101110 : sin = 01010111011; 1101111 : sin = 01011000001; 1110000 : sin = 01011000111; 1110001 : sin = 01011001101; 1110010 : sin = 01011010011; 1110011 : sin = 01011011001; 1110100 : sin = 01011011111; 1110101 : sin = 01011100101; 1110110 : sin = 01011101011; 1110111 : sin = 01011110001; 1111000 : sin = 01011110111; 1111001 : sin = 01011111101; 1111010 : sin = 01100000011; 1111011 : sin = 01100001001; 1111100 : sin = 01100001111; 1111101 : sin = 01100010101; 1111111 : sin = 01100100001; default : sin = 00000000000; endcaseendmodule

Page 287: PrecisionRTL Style

MemorySynchronous ROM

Precision Synthesis Style Guide, 2011a Update2 287November 2011

Synchronous ROMThis is an example of synchronous read-only memory.

The ROM will map into block RAM resources, if available in the target device technology.

VHDL

The HDL source file shown below is named rom_to_blockram.vhd and is located in theexamples directory, as noted in “Memory Coding Examples” on page 265.

library ieee;use ieee.std_logic_1164.all;use ieee.std_logic_arith.all;use ieee.std_logic_unsigned.all;

entity rom_to_blockram is generic ( addr_width_c : integer := 6; data_width_c : integer := 16); port( clk : in std_logic; addr : in std_logic_vector(addr_width_c-1 downto 0); dout : out std_logic_vector(data_width_c-1 downto 0) );end entity rom_to_blockram;

architecture rtl of rom_to_blockram is signal mem : std_logic_vector(15 downto 0); signal reg_addr : std_logic_vector(addr_width_c-1 downto 0); attribute rom_block : boolean; attribute rom_block of mem : signal is TRUE;begin process (clk) begin if (clk’event and clk = ‘1’) then dout <= mem ; reg_addr <= addr; end if; end process;

process (reg_addr) begin CASE reg_addr IS WHEN “000000” => mem <= “1111101100110100”; WHEN “000001” => mem <= “0000101011011110”; WHEN “000010” => mem <= “1101110110101000”; WHEN “000011” => mem <= “1101110111010110”; WHEN “000100” => mem <= “0111101000000010”; WHEN “000101” => mem <= “0011110000111010”; WHEN “000110” => mem <= “0110101010111000”; WHEN “000111” => mem <= “0101001110110100”; WHEN “001000” => mem <= “0011111110111110”; WHEN “001001” => mem <= “1111100110000100”; WHEN “001010” => mem <= “0111100111101100”; WHEN “001011” => mem <= “1111100101101000”; WHEN “001100” => mem <= “1101101100111000”; WHEN “001101” => mem <= “0110110111100100”; WHEN “001110” => mem <= “1000001011100010”;

Page 288: PrecisionRTL Style

Precision Synthesis Style Guide, 2011a Update2288

MemorySynchronous ROM

November 2011

WHEN “001111” => mem <= “1111110010111000”; WHEN “010000” => mem <= “1000010100110000”; WHEN “010001” => mem <= “0010100010111000”; WHEN “010010” => mem <= “1010101010101010”; WHEN “010011” => mem <= “1111010100010100”; WHEN “010100” => mem <= “1110001110000100”; WHEN “010101” => mem <= “0111010000010000”; WHEN “010110” => mem <= “1110000000110010”; WHEN “010111” => mem <= “0010111001010000”; WHEN “011000” => mem <= “0100100011001100”; WHEN “011001” => mem <= “0011010110111010”; WHEN “011010” => mem <= “0101100100101100”; WHEN “011011” => mem <= “1101000111111000”; WHEN “011100” => mem <= “0101100010001100”; WHEN “011101” => mem <= “1010001011001100”; WHEN “011110” => mem <= “1001011101111000”; WHEN “011111” => mem <= “0111011100010000”; WHEN “100000” => mem <= “0111011111011010”; WHEN “100001” => mem <= “1000110110101100”; WHEN “100010” => mem <= “1001111100001000”; WHEN “100011” => mem <= “0010000001011100”; WHEN “100100” => mem <= “1111001010000000”; WHEN “100101” => mem <= “1001011010010010”; WHEN “100110” => mem <= “1000010001001010”; WHEN “100111” => mem <= “0011000100110000”; WHEN “101000” => mem <= “0011110010101100”; WHEN “101001” => mem <= “0000011010011000”; WHEN “101010” => mem <= “1111101100010110”; WHEN “101011” => mem <= “0110000010101110”; WHEN “101100” => mem <= “0011100100010010”; WHEN “101101” => mem <= “1001110101000000”; WHEN “101110” => mem <= “0000111000001010”; WHEN “101111” => mem <= “0011001110010100”; WHEN “110000” => mem <= “1110101110011010”; WHEN “110001” => mem <= “0001100001110110”; WHEN “110010” => mem <= “1010011001111100”; WHEN “110011” => mem <= “0000010010000100”; WHEN “110100” => mem <= “1000000010000010”; WHEN “110101” => mem <= “1011111100100000”; WHEN “110110” => mem <= “0000110011011100”; WHEN “110111” => mem <= “0010001011000110”; WHEN “111000” => mem <= “0001000000001000”; WHEN “111001” => mem <= “1011011000100000”; WHEN “111010” => mem <= “0000100110100010”; WHEN “111011” => mem <= “0000111110011100”; WHEN “111100” => mem <= “0000011010010100”; WHEN “111101” => mem <= “0110011111100010”; WHEN “111110” => mem <= “1100111010110010”; WHEN “111111” => mem <= “0110000111111010”; WHEN OTHERS => mem <= “0000000000000000”; END CASE ; end process;

end architecture rtl;

Page 289: PrecisionRTL Style

MemorySynchronous ROM

Precision Synthesis Style Guide, 2011a Update2 289November 2011

Verilog

The HDL source file shown below is named rom_to_blockram.v and is located in theexamples directory, as noted in “Memory Coding Examples” on page 265.

‘define WIDTH_A 6‘define WIDTH_D 16‘define RAM_DEPTH 256module rom_to_blockram ( addr, clk, dout ); input [‘WIDTH_A-1:0] addr; input clk; reg [‘WIDTH_A-1:0] reg_addr; reg [‘WIDTH_D-1:0] mem; output reg [‘WIDTH_D-1:0] dout;

//pragma attribute mem rom_block TRUEalways @ (posedge clk) begin dout <= mem; reg_addr <= addr;end

always @(reg_addr ) begin case (reg_addr ) 6’b000000 : mem = 16’b1111101100110100; 6’b000001 : mem = 16’b0000101011011110; 6’b000010 : mem = 16’b1101110110101000; 6’b000011 : mem = 16’b1101110111010110; 6’b000100 : mem = 16’b0111101000000010; 6’b000101 : mem = 16’b0011110000111010; 6’b000110 : mem = 16’b0110101010111000; 6’b000111 : mem = 16’b0101001110110100; 6’b001000 : mem = 16’b0011111110111110; 6’b001001 : mem = 16’b1111100110000100; 6’b001010 : mem = 16’b0111100111101100; 6’b001011 : mem = 16’b1111100101101000; 6’b001100 : mem = 16’b1101101100111000; 6’b001101 : mem = 16’b0110110111100100; 6’b001110 : mem = 16’b1000001011100010; 6’b001111 : mem = 16’b1111110010111000; 6’b010000 : mem = 16’b1000010100110000; 6’b010001 : mem = 16’b0010100010111000; 6’b010010 : mem = 16’b1010101010101010; 6’b010011 : mem = 16’b1111010100010100; 6’b010100 : mem = 16’b1110001110000100; 6’b010101 : mem = 16’b0111010000010000; 6’b010110 : mem = 16’b1110000000110010; 6’b010111 : mem = 16’b0010111001010000; 6’b011000 : mem = 16’b0100100011001100; 6’b011001 : mem = 16’b0011010110111010; 6’b011010 : mem = 16’b0101100100101100; 6’b011011 : mem = 16’b1101000111111000; 6’b011100 : mem = 16’b0101100010001100; 6’b011101 : mem = 16’b1010001011001100; 6’b011110 : mem = 16’b1001011101111000; 6’b011111 : mem = 16’b0111011100010000; 6’b100000 : mem = 16’b0111011111011010; 6’b100001 : mem = 16’b1000110110101100; 6’b100010 : mem = 16’b1001111100001000;

Page 290: PrecisionRTL Style

Precision Synthesis Style Guide, 2011a Update2290

MemorySynchronous ROM

November 2011

6’b100011 : mem = 16’b0010000001011100; 6’b100100 : mem = 16’b1111001010000000; 6’b100101 : mem = 16’b1001011010010010; 6’b100110 : mem = 16’b1000010001001010; 6’b100111 : mem = 16’b0011000100110000; 6’b101000 : mem = 16’b0011110010101100; 6’b101001 : mem = 16’b0000011010011000; 6’b101010 : mem = 16’b1111101100010110; 6’b101011 : mem = 16’b0110000010101110; 6’b101100 : mem = 16’b0011100100010010; 6’b101101 : mem = 16’b1001110101000000; 6’b101110 : mem = 16’b0000111000001010; 6’b101111 : mem = 16’b0011001110010100; 6’b110000 : mem = 16’b1110101110011010; 6’b110001 : mem = 16’b0001100001110110; 6’b110010 : mem = 16’b1010011001111100; 6’b110011 : mem = 16’b0000010010000100; 6’b110100 : mem = 16’b1000000010000010; 6’b110101 : mem = 16’b1011111100100000; 6’b110110 : mem = 16’b0000110011011100; 6’b110111 : mem = 16’b0010001011000110; 6’b111000 : mem = 16’b0001000000001000; 6’b111001 : mem = 16’b1011011000100000; 6’b111010 : mem = 16’b0000100110100010; 6’b111011 : mem = 16’b0000111110011100; 6’b111100 : mem = 16’b0000011010010100; 6’b111101 : mem = 16’b0110011111100010; 6’b111110 : mem = 16’b1100111010110010; 6’b111111 : mem = 16’b0110000111111010; default : mem = 16’b0000000000000000; endcaseend

endmodule

Page 291: PrecisionRTL Style

Precision Synthesis Style Guide, 2011a Update2 291November 2011

Chapter 9Finite State Machines

This section describes the basic form of a finite state machine description, including HDLcoding style, power-up and reset, state encoding and other issues.

Common Guidelines

Basic Requirements of a Finite State Machine (FSM)• Enumerated type definition declaring state names

• A state register that holds the current state of the machine

• A clock specification

• Specification of the state transitions

• Specification of the outputs

• Reset/set specification (necessary for initialization in synthesis)

ProcessesA state machine generally has between one and three processes. It is recommended to havethree processes, which should include the following:

1. The first process is sequential, and handles the reset condition and latches in the nextstate on the active edge of the clock, thus storing the current state of the FSM.

2. The second process is combinatorial, and consists of a case statement. This processdetermines the next state based on the current state and the inputs.

3. The third process is combinational, and is used to set outputs. Alternatively, you can setthe outputs in the second process.

Page 292: PrecisionRTL Style

Precision Synthesis Style Guide, 2011a Update2292

Finite State MachinesOptimization Issues

November 2011

Types of State MachinesThere are two basic types of state machines, Mealy and Moore. In a Moore machine, the outputsdo not directly depend on the inputs, only on the present state. In a Mealy machine, the outputsdepend directly on the present state and the inputs. In a Moore machine, there is always aregister between the inputs and the outputs. This does not have to be the case in Mealymachines.

Power Up and ResetFor simulation, the state machine will initialize into the left most value of the enumeration type,but for synthesis it is unknown in which state the machine powers up. Since Precision Synthesisdoes state encoding on the enumeration type of the state machine, the state machine could evenpower up in a state that is not even defined in VHDL. Therefore, to get simulation and synthesisconsistency, it is very important to supply a reset to the state machine.

Optimization Issues

Inferred LatchesThe assignments to outputs and next_state in the state transition process can create unintendedlatches if not properly handled. The languages define that any signal that is not assignedanything must retain its value. This means that if you forget to assign something to an output (orthe next state) under a certain condition in the case statement, the synthesis tools will have topreserve the value.

Since the state transition process is not clocked, latches will have to be generated. You couldeasily forget to assign an output if the value does not matter. The synthesis tools will warn youabout this, since it is a common user error in VHDL: Make sure to always assign something tothe next state and the state machine outputs under every condition in the process to avoid thisproblem. To be absolutely sure, you could also assign a value to the signal at the very beginningof the process (before the start of the case statement).

Graphical state-machine entry tools often generate state machine descriptions that do not alwaysassign values to the outputs under all conditions. Precision Synthesis will issue a warning aboutthis, and you could either manually fix it in the VHDL description, or make sure you fullyspecify the state machine in the graphical entry tool. The synthesis tools cannot fill in themissing specifications, since it is bounded by the semantics of the language on this issue.

Case StatementsIn general, case statements are better suited for state machines than if-else if-else

structures. A case statement is more efficient than a if-else if-else statement because thatwould build a priority encoder to test the state (and likely more logic in the implementation).

Page 293: PrecisionRTL Style

Finite State MachinesOptimization Issues

Precision Synthesis Style Guide, 2011a Update2 293November 2011

The 'others' or 'default' clause in a case statement is synthesized if all the declared states are notused in the state machine’s case statement. Synthesis generates logic to cover these unusedstates. In addition to the 'others' or 'default' clause, if the state machine behavior for all possiblestate values are explicitly specified, then the default clause is redundant and is ignored.

Exact FSM Implementation by Disabling FSM OptimizationSometimes it is necessary to synthesize FSMs exactly as they are described in HDL with staterepresentations explicitly defined using constants. This may aid post-synthesis verification asthe FSM states are more easily identified and traced back to their HDL descriptions. Exactimplementation requires not only specification of FSM states as constant values, but alsodisabling FSM optimization. Disabling FSM optimization:

• prevents extraction and re-encoding of the state vector

• prevents removal of redundant or unreachable states

Automatic FSM extraction and advanced optimization can be disabled either globally or onindividual FSMs. To disable FSM optimization globally, use the command:

setup_design -advanced_fsm_optimization=false

or use the GUI checkbox:

Tools > Set Options > Inputs > Advanced FSM Optimization

To disable FSM optimization on an individual FSM, attach the boolean HDL code attributedisable_fsm to the net corresponding to the state vector.

NoteWhen Advanced FSM optimization is disabled, options such as encoding style, SafeFSM, and state output re-encoding do not affect the FSM synthesis.

Encoding StylesYou can allow Precision Synthesis to automatically select a Finite State Machine encoding stylefor you (the default) or you can specify a specific encoding style. The following FSM encodingschemes are available:

• Binary - Most area efficient. Will use a minimum number of registers to implement thestate vector resulting in the smallest overall area. Binary is generally not the optimalencoding for FPGAs because of the abundance of registers these devices offer. Precisionwill use Binary for small FSMs in FPGAs.

• One-hot - Provides the fastest clock to out timing. One-hot FSM encoding uses aseparate register for each bit of the state vector. The state register is connected directlyto the FSM outputs providing the fastest clock to out timing. One-hot FSMs generally

Page 294: PrecisionRTL Style

Precision Synthesis Style Guide, 2011a Update2294

Finite State MachinesOptimization Issues

November 2011

result in the fastest performance and are the most common encoding selected byPrecision's Auto selection

• Two-hot - Offers a compromise between the area advantages of binary and theperformance advantages of one-hot. Two hot FSM uses 2 register output bits driven to alogical one to define the decoding. For example, if you have an FSM with 8 states, onehot encoding requires 8 registers, a binary encoding requires 3 registers, and a two-hotencoding requires 5 registers. You should use two-hot encoding when trying to reducethe register count of a high-performance design

• Gray - Creates FSMs using Gray encoding. Gray counters are used to avoid glitchesgoing from one value to the next, however, because a general state machine has morearbitrary transitions, such behavior cannot be guaranteed. In Advanced FSMOptimization, Gray encoding encodes the longest transition sequence in decreasinglength. If Advanced FSM Optimization is not used then the Gray encoding will operatesequentially on the enumerated type. Gray encoding may reduce glitches.

• Random - When all else fails. Random encoding will use a randomly encoded statevector. Random FSM encoding is not recommended but can be used when all otherencoding schemes have failed to provide the desired result.

• Auto (default) - Automatically selects the optimal encoding. The Auto optionautomatically selects an encoding scheme for an FSM based on the target technologyand the state vector size. When using Auto, the encoding is selected based on thenumber of states in the FSM. There is a lower limit and an upper limit. Small statemachines that fall below the lower limit will be implemented as binary, state machinesbetween the lower and upper limits will be implemented as one-hot, and extremely largeFSMs will again be implemented as binary.

For many designs, one-hot encoding provides the smallest and fastest implementation of thestate machine. Precision running in the default Auto encoding mode will use binary for statemachines of 4 or less states, but will use one-hot encoding for larger state machines (States >16). For very large state machines (States > 512) Precision will revert to using binary as one bitper state becomes excessive.

Specifying the Encoding StylePrecision provides several methods for choosing the state machine encoding style:

• From the GUI menu selection Tool -> Set Options...Input dialog box

• The Tcl command setup_design -encoding

• VHDL code attributes safe_fsm and type_encoding_style

• Verilog synthesis enum pragma

Page 295: PrecisionRTL Style

Finite State MachinesOptimization Issues

Precision Synthesis Style Guide, 2011a Update2 295November 2011

Figure 9-1. Setting FSM encoding Style

You can also specify encoding from a Tcl script or the command line using the followingcommand:

setup_design -encoding=auto | binary | onehot | twohot | random | gray

And, encoding can be specified on an individual FSM basis through HDL attributes as outlinedin the next sections.

Attributes Relating to Finite State MachinesThe following attributes affect FSM implementation:

• disable_fsm (HDL only): This attribute disables Precision FSM optimization of asingle state machine. The attribute can be set on any state variable, effectively blockingFSM optimizations.

• enum_encoding (VHDL Only): The VHDL attribute enum_encoding is used tospecify the encoding of an enumerated type. The string attribute should contain theliteral representation of each state in the order they appear in the type definition.

• fsm_implementation (HDL Only): Directs Precision to attempt to place FSMs intodedicated synchronous RAM structures. Use this attribute to reduce logic consumptionby moving FSM next state logic to available synchronous RAM block(s).

• fsm_state: The value of this attribute specifies the encoding style to be used forencoding the state machine. Possible values are auto, binary, onehot, twohot, random,and gray.

Page 296: PrecisionRTL Style

Precision Synthesis Style Guide, 2011a Update2296

Finite State MachinesOptimization Issues

November 2011

• safe_fsm: Specifies that the Finite State Machine should be built as a safe FSM.

• type_encoding (VHDL Only): Specifies the style of encoding for a Finite StateMachine. This needs to be set separately for each state machine if there are multiplestate machines of different types.

• type_encoding_style (VHDL Only): Specifies the style of encoding for a Finite StateMachine. This needs to be set separately for each state machine if there are multiplestate machines of different types.

FSM Encoding using a Verilog PragmaWhen using Verilog to specify FSM encoding, assign to an attribute a set of parameters todefine an enumerated type, and then assign another attribute to the state register as follows:

// Define the states. Enum pragma allows Precision to chose encoding.parameter [2:0] /* synthesis enum my_enum_type */ st0 = 0, st1 = 1, st2 = 2,

st3 = 3, st4 = 4, st5 = 5, st6 = 6, st7 = 7;reg [2:0] /* synthesis enum binary */ state_reg, nxstate_reg ;

Valid strings for specifying the encoding style are “binary”, “onehot”, “twohot”, “random”, or“gray”. Not specifying an encoding allows Precision to encode automatically based on statecount.

Advanced FSM OptimizationThe Advanced FSM Optimization switch is on by default, you can turn it off if you want todisable the FSM extraction globally for your design.

To disable FSM optimization globally using the command:

setup_design -advanced_fsm_optimization=false

or disable the GUI checkbox:

Tools > Set Options > Inputs > Advanced FSM Optimization

To disable FSM optimization on an individual FSM, attach the boolean HDL code attributedisable_fsm to the net corresponding to the state vector.

NoteWhen Advanced FSM optimization is disabled, options such as encoding style, SafeFSM, and state output re-encoding do not affect the FSM synthesis.

Page 297: PrecisionRTL Style

Finite State MachinesSafe Finite State Machines

Precision Synthesis Style Guide, 2011a Update2 297November 2011

Safe Finite State MachinesIf the FSM is erroneously sent to an invalid state (not one of the defined states), creating a SafeFSM allows the FSM to recover to a valid state. Precision Synthesis supports the ability tocreate a Safe State Machine. A safe state machine is a state machine that a transition will alwaysbe to a valid state. Although state machine optimization will create a design which contains onlyvalid transitions under normal circumstances, in safety critical situations where, for example,radiation could potentially change one of the bits, it is important to know that the state machinewill recover to a valid state at the next clock.

For safe finite state machines, the generated implementation logic has a defined behavior foreach possible 2n values of the state variable, irrespective of the ability to reach the state.

One-hot encoded safe FSM may use larger area and increased number of registers as comparedto a binary encoded safe FSM. Therefore Precision applies binary encoding for safe FSMs bydefault. However with binary encoding for safe fsms, invalid transition to another valid ordefault state due to effects like Single Event Upset (SEU), is not detected with any indication.

If one-hot encoding is used for Safe FSMs, invalid state caused by SEU gets detected (as in0001 to 0011 for a regular one-hot encoded FSM).

Safe FSM creation is enabled using setup_design -use_safe_fsm command or set the GUIcheckbox Tools > Set Options > Inputs > Use Safe FSM (as shown in Figure 9-1 on page 295).The Use Safe FSM switch is applicable to all FSMs in the design.

To overwrite the default safe FSM binary encoding style with one-hot encoding, you can use thecommand:

setup_design -use_safe_fsm=true -encoding=onehot

How Precision Implements a Safe FSMSafe FSM operation can be selected either from the GUI, as shown in Example 9-1, oralternatively the boolean attribute safe_fsm (also FSM_COMPLETE) can be applied to theenumerated type (see Example 9-1).

The Precision tool implements SAFE_FSM as described below:

• Irrespective of the size of state machine encoding is always Binary unless there is aswitch or attribute to override. If you specified an encoding style (one-hot, two-hot,gray, binary, random), the states are encoded in the specified style.

• Unreachable states are never pruned (reference Example 9-2). State PAD is unreachableand would have been pruned under default implementation. But this state will bepreserved if safe_fsm option is exercised.

• "default" or "others" clause is specified:

Page 298: PrecisionRTL Style

Precision Synthesis Style Guide, 2011a Update2298

Finite State MachinesSafe Finite State Machines

November 2011

If in addition to the default clause, the state machine behavior for all 2n possible statevalues has also been explicitly specified, then the default clause is redundant and ispruned away. Otherwise, the default branch is preserved even if it is unreachable.Consider Example 9-2 below, under normal circumstances the state machine will alwaysbe in one of the reachable states IDLE, WAIT, EVEN, ODD, PAD. In a safe implementation,the default clause will be preserved. If the state machine ever takes the value greaterthan 3'h4, next_state will take the value IDLE and the FSM will move to the IDLE statein the next clock cycle.

• "default" clause is not specified:

For the missing choices, if any, don't care values are used to ensure a complete andunique mapping from the logical to the physical states. Refer to Example 9-3 onpage 301.

Safe FSM operation can be selected either from the GUI, as shown in Example 9-1, or by usingattributes in the code. Alternatively the boolean attribute save_fsm can be applied to theenumerated type.

To illustrate the use of safe finite state machines, here is an example:

Example 9-1. VHDL Safe Finite State Machine

LIBRARY ieee;USE ieee.std_logic_1164.all;

ENTITY safe1 ISPORT (clock, in1, in2, reset : IN std_logic;

state1, state2, state3, state4, state5, state_other : OUTstd_logic);END ;

ARCHITECTURE rtl OF safe1 ISTYPE state_t IS ( ST1, ST2, ST3, ST4, ST5 );SIGNAL state, nxstate : state_t;attribute SAFE_FSM: boolean;attribute SAFE_FSM of state_t:type is true;

BEGIN

update_state :-- Update the state on the clock edgePROCESS (reset, clock)BEGIN

IF (reset=’1’) THENstate <= ST1 ;

ELSIF clock’event and clock=’1’ THENstate <= nxstate ;

END IF ;END PROCESS;

output_sig : PROCESS (state)BEGIN

state1 <= ‘0’;state2 <= ‘0’;

Page 299: PrecisionRTL Style

Finite State MachinesSafe Finite State Machines

Precision Synthesis Style Guide, 2011a Update2 299November 2011

state3 <= ‘0’;state4 <= ‘0’;state5 <= ‘0’;state_other <= ‘0’;if( state = ST1 ) then

state1 <= ‘1’;elsif ( state = ST2 ) then

state2 <= ‘1’;elsif ( state = ST3 ) then

state3 <= ‘1’;elsif ( state = ST4 ) then

state4 <= ‘1’;elsif ( state = ST5 ) then

state5 <= ‘1’;else

state_other <= ‘1’;end if;

END PROCESS;

transitions :-- set the outputs and next statePROCESS (state, in1, in2)BEGIN

nxstate <= state;CASE state IS

WHEN ST1 =>IF in1 = ‘1’ then

nxstate <= ST2;ELSIF in2 = ‘1’ then

nxstate <= ST3;END IF;

WHEN ST2 =>IF in1 = ‘1’ then

nxstate <= ST3;ELSIF in2 = ‘1’ then

nxstate <= ST4;END IF;

WHEN ST3 =>IF in1 = ‘1’ then

nxstate <= ST4;ELSIF in2 = ‘1’ then

nxstate <= ST5;END IF;

WHEN ST4 =>IF in1 = ‘1’ then

nxstate <= ST5;ELSIF in2 = ‘1’ then

nxstate <= ST1;END IF;

WHEN ST5 =>IF in1 = ‘1’ then

nxstate <= ST1;ELSIF in2 = ‘1’ then

nxstate <= ST2;END IF;

WHEN others =>nxstate <= ST1;

END CASE;END PROCESS;

Page 300: PrecisionRTL Style

Precision Synthesis Style Guide, 2011a Update2300

Finite State MachinesSafe Finite State Machines

November 2011

END rtl;

Example 9-2. Verilog Safe Finite State Machine with Default Clause

assign incr_st = state + 1;

//Combinational block for Transition and Output Functionsalways @(state) begin next_out_err = out_err; next_state = state; case (state) IDLE: if (horz_init) begin if(out_en) next_out_err = 1’b1; next_state = incr_st; end WAIT: if (in_data_valid) next_state = incr_st; EVEN: if (horz_init) begin if(out_en) next_out_err = 1’b1; next_state = WAIT; end else if (hs_valid) begin if (eol) next_state = PAD; else next_state = incr_st; end ODD: if (horz_init) begin if(out_en) next_out_err = 1’b1; next_state = WAIT; end else if (hs_valid) begin if (eol) next_state = IDLE; else next_state = EVEN; end PAD: if (horz_init) if(out_en) next_out_err = 1’b1; else next_state = IDLE; default: next_state = IDLE; endcaseend

// Synchronous block for register inferencealways @(posedge clk) if (reset) begin state <= IDLE; out_err <= 1’b0; end else begin

Page 301: PrecisionRTL Style

Finite State MachinesSafe Finite State Machines

Precision Synthesis Style Guide, 2011a Update2 301November 2011

state <= next_state; out_err <= next_out_err; end

Example 9-3. Verilog Safe Finite State Machine with an unreachable state andwithout Default Clause

// State values using ‘define macros‘define IDLE 3’h0‘define WAIT 3’h1‘define EVEN 3’h2‘define ODD 3’h3‘define PAD 3’h4

always @(posedge clk) if (reset) begin state <= IDLE; out_err <= 1’b0; end else begin case (state) //mentor full_case IDLE: if (horz_init) state <= WAIT; WAIT: if (in_data_valid) state <= ODD; EVEN: if (horz_init) begin if(out_en) out_err <= 1’b1; state <= WAIT; end else if (hs_valid) begin if (eol) state <= IDLE; else state <= WAIT; end ODD: if (horz_init) begin if(out_en) out_err <= 1’b1; state <= WAIT; end else if (hs_valid) begin if (eol) state <= IDLE; else state <= EVEN; end PAD: if (horz_init) if(out_en) out_err <= 1’b1; else state <= IDLE; endcase end

In this Example 9-3 under safe_fsm option:

• Binary encoding will be applied.

• Unreachable state PAD will be preserved.

• Don't care values will be used to take care of the missing choices (Possible values ofstate variable "state" which have not been covered in the RTL i.e. 3'h5, 3'h6 and 3'h7)and the following logic will be generated:

Page 302: PrecisionRTL Style

Precision Synthesis Style Guide, 2011a Update2302

Finite State MachinesSafe Finite State Machines

November 2011

always @(posedge clk) if (reset) begin state <= IDLE; out_err <= 1'b0; end else begin casex (state) 3'b000: if (horz_init) state <= WAIT; 3'b001: if (in_data_valid) state <= ODD; 3'bx10: if (horz_init) begin if(out_en) out_err <= 1'b1; state <= WAIT; end else if (hs_valid) begin if (eol) state <= IDLE; else state <= WAIT; end 3'bx11: if (horz_init) begin if(out_en) out_err <= 1'b1; state <= WAIT; end else if (hs_valid) begin if (eol) state <= IDLE; else state <= EVEN; end 3'b10x: if (horz_init)

if(out_en) out_err <= 1'b1; else

state <= IDLE; endcase end

Page 303: PrecisionRTL Style

Finite State MachinesLeonardo/Precision Differences

Precision Synthesis Style Guide, 2011a Update2 303November 2011

Leonardo/Precision DifferencesIn Precision, you can also specify the encoding style using the following command:

setup_design -encoding = auto | binary | onehot | twohot | random | gray

In Leonardo, you can use the encoding variable.

Coding ExamplesThe following table shows the VHDL and Verilog examples described in this section. The codefiles are available in the Precision Synthesis software tree in the following directory:

<install_dir>/shared/examples/style_guide_hdl/Finite_State_Machines

Table 9-1. FSM Examples

Example Description

Single Process StateMachine

State machine with only one process. In this process, the state andoutput are both updated according to the current state only.

Two Process StateMachine

State machine with two processes. The first process is used to updatethe state, based on the input. The second process updates the output,based on the current state.

Three Process StateMachine

The first process updates the current state according to the next state.The second process sets the next state based on the input. The thirdprocess updates the output based on the current state.

Moore State Machine Moore style state machine. The defining factor of a Moore statemachine is that the output is dependent only on the current state, andnot dependent on the input. Moore state machines can have one tothree processes.

Mealy State Machine Mealy state machine. The defining factor of a Mealy state machine isthat the output is dependent on the input. Mealy state machines canhave either two or three processes.

Example 9-1 VHDL Safe Finite State Machine

Example 9-2 Verilog Safe Finite State Machine with Default Clause

Example 9-3 Verilog Safe Finite State Machine with an unreachable state andwithout Default Clause

Page 304: PrecisionRTL Style

Precision Synthesis Style Guide, 2011a Update2304

Finite State MachinesSingle Process State Machine

November 2011

Single Process State MachineState machine with only one process. In this process, the state and output are both updatedaccording to the current state only.

VHDL Verilog

LIBRARY IEEE;USE IEEE.STD_LOGIC_1164.ALL;USE IEEE.NUMERIC_STD.ALL;

ENTITY fsm_single ISPORT (a, clk, reset: IN STD_LOGIC; y: OUT STD_LOGIC);END ENTITY;

ARCHITECTURE rtl OF fsm_single ISTYPE state_type IS (s0, s1, s2, s3);SIGNAL state: state_type;BEGIN

PROCESS (clk, reset)BEGINIF (reset = ‘1’) THEN state <= s0; y <= a;ELSIF (clk’EVENT AND clk = ‘1’) THEN CASE state IS WHEN s0 => state <= s1; y <= ‘1’; WHEN s1 => state <= s2; y <= ‘1’; WHEN s2 => state <= s3; y <= ‘0’; WHEN s3 => state <= s0; y <= ‘0’; END CASE;END IF;END PROCESS;END ARCHITECTURE;

module fsm_single (a, clk, reset, y);

input a, clk, reset;output y;

reg y;reg [1:0] state;

always @ (posedge clk or posedge reset) if (reset) begin state = 2’b00; y = a; end else case (state) 2’b00: begin state = 2’b01; y = 1’b1; end 2’b01: begin state = 2’b10; y = 1’b1; end 2’b10: begin state = 2’b11; y = 1’b0; end 2’b11: begin state = 2’b00; y = 1’b0; end endcaseendmodule

Page 305: PrecisionRTL Style

Finite State MachinesTwo Process State Machine

Precision Synthesis Style Guide, 2011a Update2 305November 2011

Two Process State MachineState machine with two processes. The first process is used to update the state, based on theinput. The second process updates the output, based on the current state.

VHDL Verilog

LIBRARY IEEE;USE IEEE.STD_LOGIC_1164.ALL;USE IEEE.NUMERIC_STD.ALL;

ENTITY fsm_two ISPORT (a, clk, reset: IN STD_LOGIC;

y: OUT STD_LOGIC);END ENTITY;

ARCHITECTURE rtl OF fsm_two IS TYPE state_type IS (s0, s1, s2, s3); SIGNAL state: state_type;BEGIN

PROCESS (clk, reset)BEGIN IF (reset = ‘1’) THEN state <= s0; ELSIF (clk’EVENT AND clk = ‘1’) THEN

CASE state ISWHEN s0 =>

IF (a = ‘1’) THENstate <= s1;

ELSEstate <= s0;

END IF;WHEN s1 =>

IF (a = ‘1’) THENstate <= s2;

ELSEstate <= s0;

END IF;WHEN s2 =>

IF (a = ‘1’) THENstate <= s3;

ELSEstate <= s0;

END IF;WHEN s3 =>

state <= s0;END CASE;

END IF;END PROCESS;

PROCESS (state)BEGIN

CASE state IS WHEN s0 => y <= ‘1’; WHEN s1 => y <= ‘1’; WHEN s2 => y <= ‘0’; WHEN s3 => y <= ‘0’; END CASE;END PROCESS;END ARCHITECTURE;

module fsm_two (a, clk, reset, y);

input a, clk, reset;output y;

reg y;reg [1:0] state;

always @ (posedge clk or posedge reset)begin if (reset) begin state = 2’b00; end else begin case (state) 2’b00: begin if (a) state = 2’b01; else state = 2’b00; end 2’b01: begin if (a) state = 2’b10; else state = 2’b00; end 2’b10: begin if (a) state = 2’b11; else state = 2’b00; end 2’b11: state = 2’b00; default: state = state; endcase endend

always @ (state)begin case (state) 2’b00: y = 1’b1; 2’b01: y = 1’b1; 2’b10: y = 1’b0; 2’b11: y = 1’b0; default:y = y; endcaseend

endmodule

Page 306: PrecisionRTL Style

Precision Synthesis Style Guide, 2011a Update2306

Finite State MachinesThree Process State Machine

November 2011

Three Process State MachineThe first process updates the current state according to the next state. The second process setsthe next state based on the input. The third process updates the output based on the current state.

Example 9-4. VHDL Three Process FSM

LIBRARY IEEE;USE IEEE.std_logic_1164.ALL;USE IEEE.numeric_std.ALL;

ENTITY fsm_three ISPORT ( a, clk, reset: IN STD_LOGIC; y: OUT STD_LOGIC);END ENTITY;

ARCHITECTURE rtl OF fsm_three IS TYPE state_type IS (s0, s1, s2, s3); SIGNAL state, nextstate : state_type;BEGIN

PROCESS (clk, reset)BEGIN IF (reset = ‘1’) THEN state <= s0; ELSIF (clk’EVENT AND clk = ‘1’) THEN state <= nextstate; END IF;END PROCESS;

PROCESS (state, a)BEGINCASE state IS

WHEN s0 =>IF (a = ‘1’) THEN

nextstate <= s1;ELSE

nextstate <= s0;END IF;

WHEN s1 =>IF (a = ‘1’) THEN

nextstate <= s2;ELSE

nextstate <= s0;END IF;

WHEN s2 =>IF (a = ‘1’) THEN

nextstate <= s3;ELSE

nextstate <= s0;END IF;

WHEN s3 =>nextstate <= s0;

END CASE;END PROCESS;

Page 307: PrecisionRTL Style

Finite State MachinesThree Process State Machine

Precision Synthesis Style Guide, 2011a Update2 307November 2011

PROCESS (state)BEGIN

CASE state IS WHEN s0 => y <= ‘1’; WHEN s1 => y <= ‘1’; WHEN s2 => y <= ‘0’; WHEN s3 => y <= ‘0’; END CASE;END PROCESS;

END ARCHITECTURE;

Example 9-5. Verilog Three Process FSM

module fsm_three (a, clk, reset, y);

input a, clk, reset;output y;

reg y;reg [1:0] state, next_state;

always @ (posedge clk or posedge reset)begin if (reset) state = 2’b00; else state = next_state;end

always @ (state or a)begin case (state) 2’b00: begin if (a) next_state = 2’b01; else next_state = 2’b00; end 2’b01: begin if (a) next_state = 2’b10; else next_state = 2’b00; end 2’b10: begin if (a) next_state = 2’b11; else

Page 308: PrecisionRTL Style

Precision Synthesis Style Guide, 2011a Update2308

Finite State MachinesThree Process State Machine

November 2011

next_state = 2’b00; end 2’b11: next_state = 2’b00; default: next_state = state; endcaseend

always @ (state)begin case (state) 2’b00: y = 1’b1; 2’b01: y = 1’b1; 2’b10: y = 1’b0; 2’b11: y = 1’b0; default:y = y; endcaseend

endmodule

Page 309: PrecisionRTL Style

Finite State MachinesMoore State Machine

Precision Synthesis Style Guide, 2011a Update2 309November 2011

Moore State MachineMoore style state machine. The defining factor of a Moore state machine is that the output isdependent only on the current state, and not dependent on the input. Moore state machines canhave one to three processes.

Example 9-6. VHDL Moore State Machine

LIBRARY IEEE;USE IEEE.std_logic_1164.ALL;USE IEEE.numeric_std.ALL;

ENTITY moore IS PORT(clk,cs,refresh : IN STD_LOGIC; ras, cas, ready : OUT STD_LOGIC);END moore;

ARCHITECTURE rtl OF moore IS TYPE state_type IS (s0, s1, s2, s3, s4); SIGNAL present_state : state_type;BEGIN PROCESS (clk) BEGIN IF clk’EVENT AND clk = ‘1’ THEN CASE present_state IS WHEN s0 => IF (refresh = ‘1’) THEN present_state <= s3; ELSIF (cs <= ‘1’) THEN present_state <= s1; ELSE present_state <= s0; END IF; WHEN s1 => present_state <= s2; WHEN s2 => IF (cs = ‘0’) THEN present_state <= s0; ELSE present_state <= s2; END IF; WHEN s3 => present_state <= s4; WHEN s4 => present_state <= s0; END CASE ; END IF; END PROCESS; PROCESS (present_state) BEGIN CASE present_state IS WHEN s0 => ras <= ‘1’; cas <= ‘1’; ready <= ‘1’; WHEN s1 => ras <= ‘0’;

Page 310: PrecisionRTL Style

Precision Synthesis Style Guide, 2011a Update2310

Finite State MachinesMoore State Machine

November 2011

cas <= ‘1’; ready <= ‘0’; WHEN s2 => ras <= ‘0’; cas <= ‘0’; ready <= ‘0’; WHEN s3 => ras <= ‘1’; cas <= ‘0’; ready <= ‘0’; WHEN s4 => ras <= ‘0’; cas <= ‘0’; ready <= ‘0’; END CASE; END PROCESS;END ARCHITECTURE;

Example 9-7. Verilog Moore State Machine

module moore (clk, cs, refresh, ras, cas, ready); input clk, cs, refresh; output ras, cas, ready; parameter [2:0] /* synthesis enum estates */ s0 = 0, s1 = 1, s2 = 2, s3 = 3, s4 = 4; reg [2:0] /* synthesis enum estates */ present_state; reg ras, cas, ready; always @ (posedge clk) begin case (present_state) s0 : begin if (refresh) present_state = s3; else if (cs) present_state = s1; else present_state = s0; end s1 : begin present_state = s2; end s2 : begin if (~cs) present_state = s0; else present_state = s2; end s3 : begin present_state = s4; end s4 : begin present_state = s0; end default : begin present_state = s0; end

Page 311: PrecisionRTL Style

Finite State MachinesMoore State Machine

Precision Synthesis Style Guide, 2011a Update2 311November 2011

endcase end always @ (present_state) begin case (present_state) s0 : begin ras = 1’b1; cas = 1’b1; ready = 1’b1; end s1 : begin ras = 1’b0; cas = 1’b1; ready = 1’b0; end s2 : begin ras = 1’b0; cas = 1’b0; ready = 1’b0; end s3 : begin ras = 1’b1; cas = 1’b0; ready = 1’b0; end s4 : begin ras = 1’b0; cas = 1’b0; ready = 1’b0; end default : begin ras = 1’bX; cas = 1’bX; ready = 1’bX; end endcase endendmodule

Page 312: PrecisionRTL Style

Precision Synthesis Style Guide, 2011a Update2312

Finite State MachinesMealy State Machine

November 2011

Mealy State MachineMealy state machine. The defining factor of a Mealy state machine is that the output isdependent on the input. Mealy state machines can have either two or three processes.

Example 9-8. VHDL Mealy State Machine

LIBRARY IEEE;USE IEEE.std_logic_1164.ALL;USE IEEE.numeric_std.ALL;

ENTITY mealy IS PORT(clk,cs,refresh,reset : IN STD_LOGIC; ras,cas,ready : OUT STD_LOGIC);END mealy;

ARCHITECTURE rtl OF mealy IS TYPE state_type IS (s0, s1, s2, s3, s4); SIGNAL present_state,next_state : state_type;BEGIN

PROCESS (clk, reset)BEGIN IF (reset=’1’) THEN present_state <= s0; ELSIF (clk’EVENT AND clk = ‘1’) THEN present_state <= next_state; END IF;END PROCESS;

PROCESS (present_state,refresh,cs)BEGIN CASE present_state IS WHEN s0 => ras <= ‘1’; cas <= ‘1’; ready <= ‘1’; IF (refresh = ‘1’) THEN next_state <= s3; ELSIF (cs = ‘1’) THEN next_state <= s1; ELSE next_state <= s0; END IF; WHEN s1 => ras <= ‘0’; cas <= ‘1’; ready <= ‘0’; next_state <= s2; WHEN s2 => ras <= ‘0’; cas <= ‘0’; ready <= ‘0’; IF (cs = ‘0’) THEN next_state <= s0; ELSE

Page 313: PrecisionRTL Style

Finite State MachinesMealy State Machine

Precision Synthesis Style Guide, 2011a Update2 313November 2011

next_state <= s2; END IF; WHEN s3 => ras <= ‘1’; cas <= ‘0’; ready <= ‘0’; next_state <= s4; WHEN s4 => ras <= ‘0’; cas <= ‘0’; ready <= ‘0’; next_state <= s0; END CASE ;END PROCESS ;END ARCHITECTURE ;

Example 9-9. Verilog Mealy State Machine

module mealy (clk, cs, refresh, reset, ras, cas, ready); input clk, cs, refresh, reset; output ras, cas, ready; parameter [2:0] /* synthesis enum estates */ s0 = 0, s1 = 1, s2 = 2, s3 = 3, s4 = 4; reg [2:0] /* synthesis enum binary */ present_state, next_state; reg ras, cas, ready; always @ (posedge clk or posedge reset) if (reset)

present_state = s0; else present_state = next_state; always @ (present_state or refresh or cs) begin next_state = s0; ras = 1’bX; cas = 1’bX; ready = 1’bX; case (present_state) s0 : begin ras = 1’b1; cas = 1’b1; ready = 1’b1; if (refresh) next_state = s3; else if (cs) next_state = s1; else next_state = s0; end s1 : begin ras = 1’b0; cas = 1’b1; ready = 1’b0; next_state = s2; end s2 : begin

Page 314: PrecisionRTL Style

Precision Synthesis Style Guide, 2011a Update2314

Finite State MachinesMealy State Machine

November 2011

ras = 1’b0; cas = 1’b0; ready = 1’b0; if (~cs) next_state = s0; else next_state= s2; end s3 : begin ras = 1’b1; cas = 1’b0; ready = 1’b0; next_state = s4; end s4 : begin ras = 1’b0; cas = 1’b0; ready = 1’b0; next_state = s0; end endcase endendmodule

Page 315: PrecisionRTL Style

Precision Synthesis Style Guide, 2011a Update2 315November 2011

Chapter 10DSP Blocks

Precision RTL Synthesis detects a DSP operator from the style of the RTL code at a technology-independent level, then maps the element to a generic DSP operator in the RTL database atcompile time. During the technology-mapping phase of synthesis, Precision maps the genericDSP operator to the technology specific DSP block. Depending upon the pipeline register andaccumulator resources available within the target device’s DSP block, Precision willautomatically absorb them into the DSP block where possible.

Common Guidelines

Basic Requirements for DSP Inference• Use the default compiler. If you have 2004c Compile Mode enabled, disable it in Tool ->

Set Options... -> Input dialog box -or- use the command:

setup_design -2004c_compile_mode=false

(default compiler enabled)

• Use the dedicated_mult attribute set “ON” to enable mapping into DSP blocks,otherwise multipliers will be mapped into logic and carry chain resources (default isdedicated_mult=ON)

• Reset handling should match the technology requirement for synchronous orasynchronous signal behavior

General Inference SupportThere are a great many possible operations that fall into the DSP arena, the most common aresupported across all DSP resource rich technologies:

• MULT

• MULT-ACC

• MULT-ADD

• MULT-ADDSUB

• MULT-ACC-ADDSUB

Page 316: PrecisionRTL Style

Precision Synthesis Style Guide, 2011a Update2316

DSP BlocksCommon Guidelines

November 2011

Inference and InstantiationPrecision Synthesis supports Verilog 2001 and VHDL DSP cell instantiation just like any otherspecific technology cells. Both DSP cell instantiation and specific vendor DSP netlistgeneration should be avoided due to their complex nature and technology dependence.Precision Synthesis supports advanced DSP inferencing across different vendors andtechnologies, and is the recommended approach.

DSP inferencing relies on use of the default compiler and the dedicated_mult attribute. If youhave 2004c Compile Mode enabled, disable it from the menu selection Tool -> Set Options... ->Input dialog box, or use the command:

setup_design -2004c_compile_mode=false.

Add the attribute named dedicated_mult to multipliers in your design to control inferencemapping. Set the value of dedicated_mult to “ON” for mapping into DSP blocks (default), usethe value “OFF” to map to carry-chain logic and LUTs.

set_attribute -name dedicated_mult -value ON (default)

set_attribute -name dedicated_mult -value OFF

If you prefer to use the GUI, right-click on a multiplier operator and choose Use DedicatedMultiplier -> ON from the popup menu.

Figure 10-1. Adding dedicated_mult via the GUI

Page 317: PrecisionRTL Style

DSP BlocksCommon Guidelines

Precision Synthesis Style Guide, 2011a Update2 317November 2011

Reset Design RequirementsFor optimal results, carefully compare the reset signal behavior in your design to the style usedin the target device DSP block, otherwise Precision will not be able to absorb registers into theDSP blocks. While the general design guideline is to use only synchronous reset inprogrammable logic design, a few devices use asynchronous reset signal behavior within theirDSP blocks, for example, Altera Stratix/Stratix II and LatticeECP.

An alternative is to avoid specifying a reset signal within your VHDL process or Verilog block:

/*-------------------------------------------------------------------------- Copyright (c) 2006 Mentor Graphics Corporation. All rights reserved.-- The following information has been generated by Mentor Graphics-- and may be freely distributed and modified.---- Design name : mult_acc---- Purpose : This design example shows how to infer a multiply-accumulate-- DSP operator using Precision synthesis tool---- Rev: 1.0-- Precision: 2005c-- Date: Jan 05 2006-----------------------------------------------------------------------*/

module mult_acc (a, b, clk, data_out); parameter sub_in_width = 9; parameter sub_out_width = 18;

input signed[sub_in_width-1:0] a; input signed[sub_in_width-1:0] b; input clk;

output signed[sub_out_width-1:0] data_out; reg signed[sub_out_width-1:0] multout_reg, accum_out; reg signed[sub_in_width-1:0] a_reg, b_reg;

always @(posedge clk) begin // set number of pipeline registers on the A, B inputs to 1 a_reg <= a; b_reg <= b; // set number of pipeline registers on the mult output to 1 multout_reg <= a_reg * b_reg; // set number of pipeline registers on the accumulated output to 1 accum_out <= accum_out + multout_reg; end assign data_out = accum_out;endmodule

Page 318: PrecisionRTL Style

Precision Synthesis Style Guide, 2011a Update2318

DSP BlocksCommon Guidelines

November 2011

Vendor Specific DSP Optimizations

Xilinx Virtex-4/5 DSP48 Optimization and RetimingThe following is brief list of DSP specific inference and optimization information found in the“Designing with Xilinx Devices” chapter of the Precision Synthesis Reference Manual.

• Inferring Virtex-4/5 DSP48 cells

• Supported MULT-ADD and MULT-ACC modes implemented in single DSP48 cells

• Virtex-5 extended capabilities

• DSP Retiming for select Xilinx technologies

o Register repositioning across a single DSP

o Register repositioning inside a single DSP

o Register repositioning across a cascaded DSP chain

o Outside register repositioning into the DSP block

o Supported technologies for DSP retiming

o DSP retiming in different precision flows

Page 319: PrecisionRTL Style

DSP BlocksAttributes Relating to DSP Blocks

Precision Synthesis Style Guide, 2011a Update2 319November 2011

Attributes Relating to DSP BlocksThe following attributes affect DSP implementation:

• dedicated_mult: Use the dedicated_mult attribute to control whether or not theModgen operator “mult” utilizes DSP block or multiplier resources in the targettechnology. If dedicated_mult=ON, then both DSP blocks (or multipliers) and carrychains can be inferred (based on size). If set to OFF, then only carry chains will beinferred and multiplier operations will be mapped into logic.

For a complete description of the dedicated_mult attribute, see dedicated_mult in theAttributes section of the Precision RTL Synthesis Reference Manual.

• frontend_dissolve (HDL only): Adding the attribute or pragma frontend_dissolve

directly into HDL source files may significantly improve QoR on some hierarchicalDSP designs. The heuristic of this attribute will be automated into a future release. Donot use this attribute on blackboxes or technology cells that you intend to preserve, or onany other type of designs beside DSP.

• use_resource: The most aggressive DSP mapping can be enabled using theuse_resource attribute in your Precision constraints file. Add use_resource with thevalue DSP to the adders and incrementers in your design with these constraint file lines:

set_attribute -design rtl -name use_resource -value DSP -instance [get_cells -hier *add*]set_attribute -design rtl -name use_resource -value DSP -instance [get_cells -hier *inc*]

Page 320: PrecisionRTL Style

Precision Synthesis Style Guide, 2011a Update2320

DSP BlocksDSP Code Examples

November 2011

DSP Code ExamplesThe following table shows the VHDL and Verilog examples described in this section. The codefiles are available in the Precision Synthesis software tree in the following directory:

<install_dir>/shared/examples/style_guide_hdl/dsp/inferred_dsp<install_dir>/shared/examples/style_guide_hdl/dsp/instantiated_dsp

Table 10-1. DSP Code Examples

Example Description

MULT-ADD Example of coding style for MULT-ADD, in which PrecisionSynthesis will infer MULT_ADD operator and map theMULTIPLIER with pipeline registers, and adder logic into a singleDSP block.

MULT-ADDSUB Sample coding style for MULT-ADDSUB, in which PrecisionSynthesis will infer MULT_ADDSUB operator and mapMULTIPLIER with pipeline registers, and ADDSUB logic into asingle DSP block.

MULT-ACC This is a simple example of MULT_ACC operator, both MULT andADD_SUB operator will be inferred and pulled into a single DSPblock

MULT-ACC-ADDSUB

This is an example of MULT-ACC-ADDSUB operator, both MULTand ADD_SUB operator will be inferred and pulled into a single DSPblock

Fully Pipelined 35x18Multiplier

This fully pipelined 35 x 18 bit multiplier can be modeled byPrecision Synthesis without having to use vendor’s CoreGen, MegaWizards, or manual instantiations. The same source code can then beconveniently used to target different devices.

Instantiating DSPFunctions

Both DSP cell instantiation and specific vendor DSP netlistgeneration should be avoided due to their complex nature andtechnology dependence. Precision Synthesis supports Verilog 2001and VHDL DSP cell instantiation just like any other technologyspecific cells. We recommend using Precision Synthesis to infer all ofthe DSP functions when possible.

Page 321: PrecisionRTL Style

DSP BlocksMULT-ADD

Precision Synthesis Style Guide, 2011a Update2 321November 2011

MULT-ADDExample of coding style for MULT-ADD, in which Precision Synthesis will infer MULT_ADDoperator and map the MULTIPLIER with pipeline registers, and adder logic into a single DSPblock.

Figure 10-2. DSP MULT-ADD

Example 10-1. Verilog DSP MULT-ADD

module mult_add (clk, load, dataa, datab, datac, preg);parameter sub_in_width = 18;parameter sub_out_width = 48;

input signed[sub_in_width-1:0] dataa;input signed[sub_in_width-1:0] datab;input signed[sub_out_width-1:0] datac;input clk, load;

output signed[sub_out_width-1:0] preg;

reg signed[sub_out_width-1:0] mult0_result;reg signed[sub_in_width-1:0] reg_dataa;reg signed[sub_in_width-1:0] reg_datab;reg signed[sub_in_width-1:0] reg_datab1;reg signed[sub_out_width-1:0] reg_datac;reg signed[sub_out_width-1:0] preg;wire signed[sub_out_width-1:0] result;

always @(posedge clk)begin reg_datac <= datac; reg_dataa <= dataa; reg_datab <= datab; reg_datab1 <= reg_datab; mult0_result <= reg_dataa * reg_datab1; preg <= result;endassign result = load ? reg_datac : reg_datac + mult0_result;

endmodule

Page 322: PrecisionRTL Style

Precision Synthesis Style Guide, 2011a Update2322

DSP BlocksMULT-ADD

November 2011

Example 10-2. VHDL DSP MULT-ADD

----------------------------------------------------------------------------- Copyright (c) 2006 Mentor Graphics Corporation. All rights reserved.-- The following information has been generated by Mentor Graphics-- and may be freely distributed and modified.---- Design name : mult_add-- Purpose : This design example shows how to infer a mult_add-- DSP operator using Precision synthesis tool---- Rev: 1.0-- Precision: 2005c-- Date: Jan 05 2006---------------------------------------------------------------------------library ieee ;USE ieee.std_logic_1164.all;USE ieee.std_logic_arith.all;

entity mult_add is generic (sub_in_width : integer := 18; sub_out_width : integer := 48);

port ( dataa: in signed (sub_in_width-1 downto 0) ; datab: in signed (sub_in_width-1 downto 0) ; datac: in signed (sub_out_width-1 downto 0) ; preg: out signed (sub_out_width-1 downto 0) ; load, clk: in std_logic ) ;end mult_add;

architecture rtl of mult_add is signal reg_dataa, reg_datab, reg_datab1 : signed (sub_in_width-1 downto 0); signal datac1, reg_preg, result: signed (sub_out_width-1 downto 0); signal mult0_result : signed (sub_in_width*2-1 downto 0);begin process (clk) begin if (clk’event and clk =’1’) then reg_dataa <= signed (dataa); reg_datab <= signed (datab); reg_datab1 <= reg_datab; datac1 <= signed (datac); mult0_result <= reg_dataa * reg_datab1; reg_preg <= signed (result); end if; end process;preg <= reg_preg;result <= (mult0_result + datac1) when (load = ‘1’) else (datac1);

end rtl ;

Page 323: PrecisionRTL Style

DSP BlocksMULT-ADDSUB

Precision Synthesis Style Guide, 2011a Update2 323November 2011

MULT-ADDSUBSample coding style for MULT-ADDSUB, in which Precision Synthesis will inferMULT_ADDSUB operator and map MULTIPLIER with pipeline registers, and ADDSUBlogic into a single DSP block.

Figure 10-3. DSP MULT-ADDSUB

Example 10-3. Verilog DSP MULT-ADDSUB

/*--------------------------------------------------------------------------- Copyright (c) 2006 Mentor Graphics Corporation. All rights reserved.-- The following information has been generated by Mentor Graphics-- and may be freely distributed and modified.---- Design name : mult_add_sub---- Purpose : This design example shows how to infer a multiply-add_sub-- DSP operator using Precision synthesis tool---- Rev: 1.0-- Precision: 2005c-- Date: Jan 05 2006------------------------------------------------------------------------*/

module mult_add_sub (clk, load, dataa, datab, datac, preg); parameter sub_in_width = 9; parameter sub_out_width = 18;

input signed[sub_in_width-1:0] dataa; input signed[sub_in_width-1:0] datab; input signed[sub_out_width-1:0] datac; input clk, load;

output signed[sub_out_width-1:0] preg; reg signed[sub_out_width-1:0] mult0_result; reg signed[sub_in_width-1:0] reg_dataa; reg signed[sub_in_width-1:0] reg_datab; reg signed[sub_out_width-1:0] reg_datac; reg signed[sub_out_width-1:0] preg; wire signed[sub_out_width-1:0] result;

always @(posedge clk) begin // Set number of pipeline registers on the A, B, and C inputs to 1 reg_datac <= datac; reg_dataa <= dataa; reg_datab <= datab; // Set number of pipeline registers on the mult output to 1 mult0_result <= reg_dataa * reg_datab; // Set number of pipeline registers on the product output to 1 preg <= result; end // Multiply-add_sub assign result = load ? reg_datac - mult0_result : reg_datac + mult0_result;

endmodule

Page 324: PrecisionRTL Style

Precision Synthesis Style Guide, 2011a Update2324

DSP BlocksMULT-ADDSUB

November 2011

Example 10-4. VHDL DSP MULT-ADDSUB

----------------------------------------------------------------------------- Copyright (c) 2006 Mentor Graphics Corporation. All rights reserved.-- The following information has been generated by Mentor Graphics-- and may be freely distributed and modified.---- Design name : mult_add_sub---- Purpose : This design example shows how to infer a multiply-add_sub-- DSP operator using Precision synthesis tool---- Rev: 1.0-- Precision: 2005c-- Date: Jan 05 2006---------------------------------------------------------------------------library ieee ;USE ieee.std_logic_1164.all;USE ieee.std_logic_arith.all;

entity mult_add_sub is generic (sub_in_width : integer := 9; sub_out_width : integer := 18);

port( dataa : in signed (sub_in_width-1 downto 0) ; datab : in signed (sub_in_width-1 downto 0) ; datac : in signed (sub_out_width-1 downto 0) ; preg : out signed (sub_out_width-1 downto 0) ; load, clk: in std_logic ) ;end mult_add_sub;

architecture RTL of mult_add_sub is signal reg_dataa, reg_datab : signed (sub_in_width-1 downto 0); signal mult0_result, reg_datac : signed (sub_out_width-1 downto 0); signal reg_preg, result : signed (sub_out_width-1 downto 0);begin process (clk) begin if (clk’event and clk =’1’) then reg_dataa <= signed (dataa); reg_datab <= signed (datab); reg_datac <= signed (datac); mult0_result <= reg_dataa * reg_datab; reg_preg <= signed (result); end if; end process;preg <= reg_preg;result <= (reg_datac - mult0_result) when (load = ‘1’) else (reg_datac + mult0_result);end RTL ;

Page 325: PrecisionRTL Style

DSP BlocksMULT-ACC

Precision Synthesis Style Guide, 2011a Update2 325November 2011

MULT-ACCThis is a simple example of MULT_ACC operator, both MULT and ADD_SUB operator willbe inferred and pulled into a single DSP block

In order to maximize inputs and outputs data width to 18 and 48 bits respectively, SIGNEDextended must be declared on both input and output port declarations

Figure 10-4. DSP MULT-ACC

Example 10-5. Verilog DSP MULT-ACC

/*-------------------------------------------------------------------------- Copyright (c) 2006 Mentor Graphics Corporation. All rights reserved.-- The following information has been generated by Mentor Graphics-- and may be freely distributed and modified.---- Design name : mult_acc---- Purpose : This design example shows how to infer a multiply-accumulate-- DSP operator using Precision synthesis tool---- Rev: 1.0-- Precision: 2005c-- Date: Jan 05 2006-----------------------------------------------------------------------*/

module mult_acc (a, b, clk, data_out); parameter sub_in_width = 9; parameter sub_out_width = 18;

input signed[sub_in_width-1:0] a; input signed[sub_in_width-1:0] b; input clk;

output signed[sub_out_width-1:0] data_out; reg signed[sub_out_width-1:0] multout_reg, accum_out; reg signed[sub_in_width-1:0] a_reg, b_reg;

always @(posedge clk) begin // set number of pipeline registers on the A, B inputs to 1 a_reg <= a; b_reg <= b; // set number of pipeline registers on the mult output to 1 multout_reg <= a_reg * b_reg; // set number of pipeline registers on the accumulated output to 1 accum_out <= accum_out + multout_reg; end assign data_out = accum_out;endmodule

Page 326: PrecisionRTL Style

Precision Synthesis Style Guide, 2011a Update2326

DSP BlocksMULT-ACC

November 2011

Example 10-6. VHDL DSP MULT-ACC

----------------------------------------------------------------------------- Copyright (c) 2006 Mentor Graphics Corporation. All rights reserved.-- The following information has been generated by Mentor Graphics-- and may be freely distributed and modified.---- Design name : mult_acc---- Purpose : This design example shows how to infer a multiply-add_sub-- DSP operator using Precision synthesis tool---- Rev: 1.0-- Precision: 2005c-- Date: Jan 05 2006---------------------------------------------------------------------------

LIBRARY ieee;USE ieee.std_logic_1164.ALL;USE ieee.std_logic_arith.ALL;USE ieee.std_logic_signed.ALL;USE ieee.std_logic_unsigned.ALL;

ENTITY mult_acc IS generic (sub_in_width : integer := 9; sub_out_width : integer := 18);

PORT (a : IN STD_LOGIC_VECTOR (sub_in_width-1 DOWNTO 0); b : IN STD_LOGIC_VECTOR (sub_in_width-1 DOWNTO 0); clk : IN STD_LOGIC; data_out: OUT STD_LOGIC_VECTOR (sub_out_width-1 DOWNTO 0));END mult_acc;

ARCHITECTURE RTL OF mult_acc IS SIGNAL a_reg, b_reg : signed (sub_in_width-1 DOWNTO 0); SIGNAL multout_reg : signed (sub_out_width-1 DOWNTO 0); SIGNAL accum_out : signed (sub_out_width-1 DOWNTO 0);BEGIN PROCESS (clk) BEGIN IF (clk’event and clk = ‘1’) THEN a_reg <= signed(a); b_reg <= signed(b); multout_reg <= a_reg * b_reg; accum_out <= accum_out + multout_reg ; END IF; END process; data_out <= std_logic_vector(accum_out);END RTL;

Page 327: PrecisionRTL Style

DSP BlocksMULT-ACC-ADDSUB

Precision Synthesis Style Guide, 2011a Update2 327November 2011

MULT-ACC-ADDSUBThis is an example of MULT-ACC-ADDSUB operator, both MULT and ADD_SUB operatorwill be inferred and pulled into a single DSP block

In order to maximize inputs and outputs data width to 18 and 48 bits respectively, SIGNEDextended must be declared on both input and output port declarations

Figure 10-5. DSP MULT-ACC-ADDSUB

Example 10-7. Verilog DSP MULT-ACC-ADDSUB

module mult_acc_addsub_example5 (dataout, dataax, dataay, clk, addsub);

parameter sub_in_width = 18;parameter sub_out_width = 48;parameter sub_in1_width = 18;‘define sub_in_width 18‘define sub_out_width 48

output signed[sub_out_width-1:0] dataout;input signed[sub_in_width-1:0] dataax, dataay;input clk, addsub;reg signed[sub_out_width-1:0] reg_dataout;

reg signed[sub_in_width-1:0] reg_dataax, reg_dataay;reg signed[sub_out_width-1:0] reg_multout;reg reg_addsub, reg_addsub_1;reg signed[sub_out_width-1:0] wire_adder_out;

always @(reg_multout or reg_dataout or reg_addsub_1)begin if ( reg_addsub_1 ) wire_adder_out <= reg_dataout + reg_multout; else wire_adder_out <= reg_dataout - reg_multout;endalways @(posedge clk)begin reg_dataout <= wire_adder_out; reg_dataax <= dataax; reg_dataay <= dataay; reg_multout <= reg_dataax * reg_dataay; reg_addsub <= addsub; reg_addsub_1 <= reg_addsub;endassign dataout = reg_dataout;endmodule

Page 328: PrecisionRTL Style

Precision Synthesis Style Guide, 2011a Update2328

DSP BlocksMULT-ACC-ADDSUB

November 2011

Example 10-8. VHDL DSP MULT-ACC-ADDSUB

library ieee ;USE ieee.std_logic_1164.all;USE ieee.std_logic_arith.all;

entity mult_acc_addsub_example5 is generic (sub_in_width : integer := 18; sub_out_width : integer := 48); port (dataax : in signed (sub_in_width-1 downto 0) ; dataay : in signed (sub_in_width-1 downto 0) ; dataout : out signed (sub_out_width-1 downto 0) ; addsub, clk : in std_logic) ;end mult_acc_addsub_example5;

architecture rtl of mult_acc_addsub_example5 is signal reg_dataax, reg_dataay : signed (sub_in_width-1 downto 0);

signal reg_dataout, wire_adder_out: signed (sub_out_width-1 downto 0); signal reg_multout : signed ((sub_in_width*2)-1 downto 0); signal reg_addsub, reg_addsub_1 : std_logic;begin process (clk) begin if (clk’event and clk =’1’) then reg_dataout <= wire_adder_out; reg_dataax <= dataax; reg_dataay <= dataay; reg_multout <= reg_dataax * reg_dataay; reg_addsub <= addsub; reg_addsub_1 <= reg_addsub; end if; end process;

process (reg_multout, reg_dataout , reg_addsub_1) begin if (reg_addsub_1 = ‘1’) then wire_adder_out <= reg_dataout + reg_multout; else wire_adder_out <= reg_dataout - reg_multout; end if; end process;dataout <= reg_dataout;end rtl;

Page 329: PrecisionRTL Style

DSP BlocksFully Pipelined 35x18 Multiplier

Precision Synthesis Style Guide, 2011a Update2 329November 2011

Fully Pipelined 35x18 MultiplierThis fully pipelined 35 x 18 bit multiplier can be modeled by Precision Synthesis withouthaving to use vendor’s CoreGen, Mega Wizards, or manual instantiations. The same sourcecode can then be conveniently used to target different devices.

Simple MULT-ACC operators can be inferred and cascaded by Precision Synthesis to design awide, fully pipelined 35 x 18 multiplier. An extra input register is required to synchronize thepartial inputs and outputs. Pipelining does increase clock latency, but this is usually not aproblem in DSP algorithms. Precision Synthesis automatically optimizes wider multipliers byperforming multiplication on partial products and intelligently cascading them.

Figure 10-6. 35x18 Multiplier Implemented in 18-bit Blocks

Figure 10-7. Partial Products used to Build 35x18 Mult

Page 330: PrecisionRTL Style

Precision Synthesis Style Guide, 2011a Update2330

DSP BlocksFully Pipelined 35x18 Multiplier

November 2011

Example 10-9. Verilog Fully Pipelined 35x18 Multiplier

/*--------------------------------------------------------------------------- Copyright (c) 2006 Mentor Graphics Corporation. All rights reserved.-- The following information has been generated by Mentor Graphics-- and may be freely distributed and modified.---- Design name : pipeline_mult_example7---- Purpose : This design example shows how to infer a pipelinedmultiplier-- DSP operator using Precision synthesis tool---- Rev: 1.0-- Precision: 2005c-- Date: Jan 05 2006-------------------------------------------------------------------------*/module pipeline_mult_example7(a, b, preg, clk);

parameter sub_in_width_a = 35;parameter sub_in_width_b = 18;parameter sub_out_width = 53;

input clk;input signed[sub_in_width_a-1:0] a;input signed[sub_in_width_b-1:0] b;output signed[sub_out_width-1:0] preg;

//a,b, and p pipelined registersreg signed[sub_in_width_a-1:0] reg_a;reg signed[sub_in_width_b-1:0] reg_b;reg signed[sub_out_width-1:0] reg_preg;

always @ (posedge clk) begin reg_a <= a; reg_b <= b; reg_preg <= reg_a * reg_b; endassign preg = reg_preg;endmodule

Page 331: PrecisionRTL Style

DSP BlocksFully Pipelined 35x18 Multiplier

Precision Synthesis Style Guide, 2011a Update2 331November 2011

Example 10-10. VHDL Fully Pipelined 35x18 Multiplier

----------------------------------------------------------------------------- Copyright (c) 2006 Mentor Graphics Corporation. All rights reserved.-- The following information has been generated by Mentor Graphics-- and may be freely distributed and modified.---- Design name : pipeline_mult_example7---- Purpose : This design example shows how to infer a pipelinedmultiplier-- DSP operator using Precision synthesis tool---- Rev: 1.0-- Precision: 2005c-- Date: Jan 05 2006---------------------------------------------------------------------------library ieee ;USE ieee.std_logic_1164.all;USE ieee.std_logic_arith.all;

entity pipeline_mult_example7 is generic (sub_in_width_a : integer := 35; sub_in_width_b : integer := 18; sub_out_width : integer := 53);

port (a : in signed (sub_in_width_a-1 downto 0); b : in signed (sub_in_width_b-1 downto 0); preg : out signed (sub_out_width-1 downto 0); clk : in std_logic );end pipeline_mult_example7;

architecture rtl of pipeline_mult_example7 is-- a, b, and p are pipelined registers signal reg_a : signed (sub_in_width_a-1 downto 0); signal reg_b : signed (sub_in_width_b-1 downto 0); signal reg_preg : signed (sub_out_width-1 downto 0);

begin process (clk) begin if (clk’event and clk =’1’) then reg_a <= a; reg_b <= b; reg_preg <= reg_a * reg_b; end if; end process;preg <= reg_preg;end rtl;

Page 332: PrecisionRTL Style

Precision Synthesis Style Guide, 2011a Update2332

DSP BlocksInstantiating DSP Functions

November 2011

Instantiating DSP FunctionsBoth DSP cell instantiation and specific vendor DSP netlist generation should be avoided due totheir complex nature and technology dependence. Precision Synthesis supports Verilog 2001and VHDL DSP cell instantiation just like any other technology specific cells. We recommendusing Precision Synthesis to infer all of the DSP functions when possible.

If neither the current inference support offered by Precision Synthesis nor Core Generator areable to meet your specific needs, we recommend contacting your local Mentor Graphics FAEfor details on how to properly instantiate these complex cells.

For the DSP48 in specific, it’s extremely important that you enable all the control signalscorrectly based on the opmode settings.

Example 10-11. Verilog DSP48 Instantiation

/*--------------------------------------------------------------------------- Copyright (c) 2006 Mentor Graphics Corporation. All rights reserved.-- The following information has been generated by Mentor Graphics-- and may be freely distributed and modified.---- Design name : mult_acc---- Purpose : This design example shows how to instantiate a DSP48 block-- using Precision synthesis tool---- Rev: 1.0-- Precision: 2005c.Prod-- Date: Jan 05 2006-------------------------------------------------------------------------*/

module mult_acc ( clk, dataa, datab, datac, result);

parameter sub_in_width = 18;parameter sub_out_width = 48;input [sub_in_width-1:0] dataa;input [sub_in_width-1:0] datab;input [sub_out_width-1:0] datac;input clk;output [sub_out_width-1:0] result;

DSP48 DSP48_1( .BCOUT(), .P(result), .PCOUT(), .A(dataa), .B(datab), .BCIN(), .C(datac), .CARRYIN(), .CARRYINSEL(), .CEA(), .CEB(), .CEC(), .CECARRYIN(), .CECINSUB(), .CECTRL(), .CEM(), .CEP(), .CLK(clk), //With OPMODE setting to 7’b0100101, P (A B+ CIN) Multiply-accumulate // mode is selected .OPMODE(7’b0100101), .PCIN(), .RSTA(), .RSTB(),

Page 333: PrecisionRTL Style

DSP BlocksInstantiating DSP Functions

Precision Synthesis Style Guide, 2011a Update2 333November 2011

.RSTC(), .RSTCARRYIN(), .RSTCTRL(), .RSTM(), .RSTP(), .SUBTRACT());

// Number of pipeline registers on the A input, 0, 1 or 2defparam DSP48_1.AREG=2;// Number of pipeline registers on the A input, 0, 1 or 2defparam DSP48_1.BREG=2;// Number of pipeline registers on the C input, 0 or 1defparam DSP48_1.CREG=1;// B input DIRECT from fabric or CASCADE from another DSP48defparam DSP48_1.B_INPUT=”DIRECT”;// Backward compatibility,NONE or MULT18X18defparam DSP48_1.LEGACY_MODE=”MULT18X18S”;// Number of pipeline registers on the P output, 0 or 1defparam DSP48_1.PREG=1;// Number of pipeline registers for the CARRYIN input, 0 or 1defparam DSP48_1.CARRYINREG =0;// Number of pipeline registers for the CARRYINSEL, 0 or 1defparam DSP48_1.CARRYINSELREG =0;// Number of pipeline registers on the SUBTRACT input, 0 or 1defparam DSP48_1.SUBTRACTREG =0;

endmodule

Example 10-12. VHDL DSP48 Instantiation

----------------------------------------------------------------------------- Copyright (c) 2006 Mentor Graphics Corporation. All rights reserved.-- The following information has been generated by Mentor Graphics-- and may be freely distributed and modified.---- Design name : mult_acc---- Purpose : This design example shows how to instantiate a DSP48 block-- using Precision synthesis tool---- Rev: 1.0-- Precision: 2005c-- Date: Jan 05 2006---------------------------------------------------------------------------

library ieee;use ieee.std_logic_1164.all;use ieee.std_logic_arith;use ieee.std_logic_signed;

entity mult_acc is generic(sub_in_width : natural := 18; sub_out_width : natural := 48); port(clk : in std_logic; dataa, datab : in std_logic_vector ( sub_in_width-1 downto 0); datac : in std_logic_vector (sub_out_width-1 downto 0); result : out std_logic_vector (sub_out_width-1 downto 0));end entity mult_acc;

Page 334: PrecisionRTL Style

Precision Synthesis Style Guide, 2011a Update2334

DSP BlocksInstantiating DSP Functions

November 2011

architecture RTL of mult_acc is

component DSP48 generic(AREG : integer := 1; B_INPUT : string := “DIRECT”; BREG : integer := 1; CARRYINREG : integer := 1; CARRYINSELREG : integer := 1; CREG : integer := 1; LEGACY_MODE : string := “MULT18X18S”; MREG : integer := 1; OPMODEREG : integer := 1; PREG : integer := 1; SUBTRACTREG : integer := 1 ); port(BCOUT : out std_logic_vector( sub_in_width-1 downto 0); P : out std_logic_vector(sub_out_width-1 downto 0); PCOUT : out std_logic_vector(sub_out_width-1 downto 0); A : in std_logic_vector( sub_in_width-1 downto 0); B : in std_logic_vector( sub_in_width-1 downto 0); BCIN : in std_logic_vector( sub_in_width-1 downto 0); C : in std_logic_vector(sub_out_width-1 downto 0); CARRYIN : in std_ulogic; CARRYINSEL : in std_logic_vector(1 downto 0); CEA : in std_ulogic; CEB : in std_ulogic; CEC : in std_ulogic; CECARRYIN : in std_ulogic; CECINSUB : in std_ulogic; CECTRL : in std_ulogic; CEM : in std_ulogic; CEP : in std_ulogic; CLK : in std_ulogic; OPMODE : in std_logic_vector(6 downto 0); PCIN : in std_logic_vector(sub_out_width-1 downto 0); RSTA : in std_ulogic; RSTB : in std_ulogic; RSTC : in std_ulogic; RSTCARRYIN : in std_ulogic; RSTCTRL : in std_ulogic; RSTM : in std_ulogic; RSTP : in std_ulogic; SUBTRACT : in std_ulogic ); end component;

signal result_out, cin, pcin : std_logic_vector(sub_out_width-1 downto 0);signal ain, bin, bcin : std_logic_vector( sub_in_width-1 downto 0);

begin

DSP48_1 : DSP48 generic map( -- Number pipeline registers on the A input, 0, 1 or 2 AREG => 2, -- B input DIRECT from fabric or CASCADE from another DSP48 B_INPUT => “DIRECT”, -- Number of pipeline registers on the B input, 0, 1 or 2 BREG => 2 , -- Number of pipeline registers for the CARRYIN input, 0 or 1

Page 335: PrecisionRTL Style

DSP BlocksInstantiating DSP Functions

Precision Synthesis Style Guide, 2011a Update2 335November 2011

CARRYINREG => 0, -- Number of pipeline registers for the CARRYINSEL, 0 or 1 CARRYINSELREG => 0, -- Number of pipeline registers on the C input, 0 or 1 CREG => 1 , -- Backward compatibility,NONE or MULT18X18 LEGACY_MODE => “MULT18X18S”, -- Number of pipeline registers on OPMODE input, 0 or 1 OPMODEREG => 0, -- Number of pipeline registers on the P output, 0 or 1 PREG => 1, -- Number of pipeline registers on the SUBTRACT input, 0 or 1 SUBTRACTREG => 0 ) port map(BCOUT => open, P => result_out, PCOUT => open, A => ain, B => bin, BCIN => bcin, C => cin, CARRYIN => ‘0’, CARRYINSEL => “00”, CEA => ‘1’, CEB => ‘1’, CEC => ‘1’, CECARRYIN => ‘0’, CECINSUB => ‘0’, CECTRL => ‘0’, CEM => ‘0’, CEP => ‘1’, CLK => clk, -- With OPMODE setting to 7’b0100101, P (A B+ CIN) -- Multiply-accumulate mode is selected OPMODE => “0100101”, PCIN => pcin, RSTA => ‘0’, RSTB => ‘0’, RSTC => ‘0’, RSTCARRYIN => ‘0’, RSTCTRL => ‘0’, RSTM => ‘0’, RSTP => ‘0’, SUBTRACT => ‘0’ );

result <= result_out(sub_out_width-1 downto 0);--ain <= X”000” & dataa;--bin <= X”000” & datab;--cin <= X”000000000” & datac;ain <= dataa;bin <= datab;cin <= datac;

end architecture RTL;

Page 336: PrecisionRTL Style

Precision Synthesis Style Guide, 2011a Update2336

DSP BlocksInstantiating DSP Functions

November 2011

Page 337: PrecisionRTL Style

Precision Synthesis Style Guide, 2011a Update2 337November 2011

Chapter 11Exemplar VHDL Package

This appendix describes the contents of the Exemplar, Precision and Synopsys VHDLpackages. These packages contain predefined types, attributes, and functions to increase adesigner’s productivity.

The Exemplar PackagesThere are a number of operations in VHDL that occur regularly. An example is the translationof vectors to integers and back. For this reason, Mentor Graphics provides packages that defineattributes, types, functions and procedures that are frequently used. Using the functions andprocedures reduces the amount of initial circuitry that is generated, compared to writing thebehavior explicitly in a user-defined function or procedure. This reduces the cpu-time forcompilation and also could result in a smaller circuit implementation due to improvedoptimization.

This section discusses the defined functionality in the Mentor Graphics packages: precision,exemplar, and exemplar_1164. The package bodies are not read by the synthesis tools; thefunctions are built-in. The packages are used for simulation only, and editing them does notchange the synthesized logic. The VHDL source for these packages is given in the filesmgc_attr.vhd, exemplar.vhd and ex_1164.vhd, respectively in the <precision install

directory>/pkgs/rtlc_psr/rtlc/auxi/packages/EXEMPLAR directory.

The exemplar_1164 package defines the same functionality as the exemplar package, butoperates on the IEEE 1164 multi-valued logic types.

If you are using the IEEE 1164 types in your VHDL description, you should include the IEEEstandard logic type definition into your VHDL description with a use clause. The VHDL sourceof the IEEE 1164 types package is in the file std_1164.vhd in the <precision install

directory>/pkgs/techdata/vhdl directory. If you also want to use the Mentor Graphicsfunctions that operate on these types, you should include the package exemplar_1164 with ause clause. For example:

library ieee;use ieee.std_logic_1164.all;library exemplar;use exemplar_1164.all;

If you do not use the IEEE 1164 types, but still want to use the Mentor Graphics functions, justinclude the package exemplar in your VHDL description with a use clause. All functions arethen defined with the predefined types bit and bit_vector, and on the four-valued typeselbit and elbit_vector.

Page 338: PrecisionRTL Style

Precision Synthesis Style Guide, 2011a Update2338

Exemplar VHDL PackageThe Exemplar Packages

November 2011

Predefined TypesThe exemplar package defines a four-valued type called elbit and its array equivalentelbit_vector. The elbit type includes the bit values ’0’, ’1’, ’X’ and ’Z’.

Mentor Graphics recommends that you use the IEEE 1164 standard logic types, and theexemplar_1164 package.

Predefined AttributesPrecision RTL Synthesis uses attributes to control synthesis of the described circuit. You canuse the set_attribute interactive shell command to set object attributes within thehierarchical database.

You may find it more convenient to define attributes in the VHDL source. The attributesrecognized by Precision’s default compiler appear in the precision_attributes package(<precision install directory>/pkgs/techdata/vhdl/mgc_attr.vhd). See “Attributes”in Precision Synthesis Reference Manual for details on each supported attribute. The followingattributes shown in Table 11-1 are recognized by the 2004c compile mode VHDL parser, anddeclared in both the exemplar and the exemplar_1164 package:

*VHDL only.

Table 11-1. Exemplar Package Attributes Recognized by the VHDL Parser

Attribute Type Description

required_time time Set required time on output

arrival_time time Set arrival_time on input

output_load real Specify load set on output

max_load real Specify max load allowed on input

clock_cycle time Specify clock length on clock pin

pulse_width time Specify pulse width on clock pin

input_drive time Specify delay/unit load for input

nobuf boolean Reject buffer insertion for a input

pin_number string Specify location of input or output pin

array_pin_number* array of strings Specify location for each bit of a bus

preserve_signal boolean Signal’s function will survive synthesis

buffer_sig string Specify explicit buffer on a pin

modgen_sel modgen_select Specify time requirement for module generatorsdriving this signal

Page 339: PrecisionRTL Style

Exemplar VHDL PackageThe Exemplar Packages

Precision Synthesis Style Guide, 2011a Update2 339November 2011

In order to set a particular attribute on a signal (or port) in VHDL, you should use the normalattribute specification statement in VHDL. Here are some examples:

Since variables do not represent one unique node in the circuit implementation (they represent adifferent circuit node after each assignment) the attributes are effective on all circuit nodes thevariable represents. This could lead to unexpected behavior. So you should be careful using theattributes on variables.

All attributes work both on single-bit signals and on arrays of bits. In the case an attribute is seton a signal that is an array of bits (bit_vector, elbit_vector or std_logic_vector) thevalue of the attribute is set to all circuit nodes in the vector. An exception is the pin_number

attribute which only operates on single bit ports. Use the array_pin_number attribute to set pinnumbers on all bits of a bus.

Refer to Chapter 2, Attributes, in the Precision RTL Synthesis Reference Manual for detailedinformation on each attribute.

Predefined FunctionsThe package exemplar defines a set of functions that are often used in VHDL for synthesis.First of all, the package defines the overloaded operators and, nand, or, nor, xor, and not forthe types elbit and elbit_vector, as well a for elbit_matrix, a two-dimensional array typeof elbit values.

The exemplar package defines a large set of functions for both the standard bit andbit_vector types. For backwards compatibility, these functions are also defined for elbit andelbit_vector types. These functions are discussed below.

library exemplar ;use exemplar.exemplar.all ; -- Include the ’exemplar’ packageentity test is

port ( my_input : in bit ;my_output : out bit_vector (5 downto 0) ;

) ;attribute pin_number of my_input:signal is "P15" ;attribute array_pin_number of my_output:signal is

("P14","P13","P12","P11","P10","P9") ;attribute required_time of my_output:signal is 5 ns ;

end test ;

architecture exemplar of test issignal internal_signal : bit ;attribute preserve_signal of internal_signal:signal is TRUE

;attribute modgen_sel of internal_signal:signal is FAST ;

begin...

Page 340: PrecisionRTL Style

Precision Synthesis Style Guide, 2011a Update2340

Exemplar VHDL PackageThe Exemplar Packages

November 2011

All functions are also defined with the IEEE 1164 types std_logic, std_ulogic,std_logic_vector, and std_ulogic_vector in the package exemplar_1164 in fileex_1164.vhd.

bool2elb(l: boolean)return std_logic;

Takes a boolean, and returns a std_logic bit. Boolean value TRUE will become std_logic

value ’1’, FALSE will become ’0’.

elb2bool(l: std_logic)return boolean;

Takes a std_logic value and returns a boolean. The std_logic value ’1’ will become TRUE,all other values become FALSE.

int2boo(l: integer)return boolean;

Takes an integer and returns a boolean. Integer value ’0’ will return FALSE, all other integervalues return TRUE.

boo2int(l: boolean)return integer;

Takes a boolean and returns an integer. Boolean value TRUE will return 1, FALSE will return 0.

evec2int(l: std_logic_vector)return integer;

Takes a vector of bits and returns the (positive) integer representation. The left most bit in thevector is assumed the MSB for the value of the integer. The vector is interpreted as an unsignedrepresentation.

int2evec (l: integer, size : integer := 32)return std_logic_vector;

Takes a integer and returns the vector representation. The size of the vector becomes equal tothe value of an optional second argument (size). If this argument is not specified, the size of thereturn vector defaults to 32. The left most bit in the resulting vector is the MSB of the returnedvalue. If the integer value of the first parameter is negative, the MSB is the sign bit.

elb2int(l: std_logic)return integer;

Takes a std_logic value and returns an integer. The std_logic value ’1’ will return integervalue 1, all other values will return integer value 0.

For all shifter functions that follow, the shift amount (r) could either be a compile time constantor not. If it is, the synthesized circuit will only consist of a re-ordering of the wires in the array.Otherwise, Precision RTL Synthesis will synthesize a shifter circuit.

sl (l: std_logic_vector; r: integer)return std_logic_vector;

Takes a vector l and an integer r and returns a vector. The resulting vector is the same size as l,but all bits of l are shifted left r places. The bits on the right side of the result vector are zero-filled. The integer r must be non-negative.

Page 341: PrecisionRTL Style

Exemplar VHDL PackageThe Exemplar Packages

Precision Synthesis Style Guide, 2011a Update2 341November 2011

sl2 (l: std_logic_vector; r: integer)return std_logic_vector;

Same as sl, but the vector l is treated as a 2-complement (signed) representation. Sign bit is theleft most bit in vector. Bits on the right are zero-filled.

sr (l: std_logic_vector; r: integer)return std_logic_vector;

Same as sl, but bits are shifted to the right side of the vector. Bits on left side are zero-filled.

sr2 (l: std_logic_vector; r: integer)return std_logic_vector;

Same as sr, but the vector l is treated as a 2-complement representation. Sign bit is the left mostbit in vector. Bits on the left side are sign-bit filled.

add (op_l, op_r: std_logic_vector)return std_logic_vector;

Takes two vectors and returns a vector. The resulting vector is one bit larger than the largest ofthe input vectors, and represents the addition of the input vectors, including the carry bit. Theleft most bit is assumed to be the MSB. The add function is a vector addition of two unsignedvectors. The smallest input vector is ’0’, extended on the MSB side to the size of the largestinput vector before addition is performed.

add2 (op_l, op_r: std_logic_vector)return std_logic_vector;

Same as add, but now the vectors are assumed to be in 2-complement representation. Sign bit isthe left most bit in the vectors. The smallest input vector is sign-bit extended on the MSB side tothe size of the largest vector before addition is performed.

sub (op_l, op_r: std_logic_vector) return std_logic_vector;

Same as add, but the subtraction function is implemented on unsigned vectors. op_r issubtracted from op_l.

Actually this is an under-flow of unsigned!

sub2 (op_l, op_r: std_logic_vector) return std_logic_vector;

add ("1011","0100") result : "01111" (add (11,4) == 15)add ("0011","100") result : "00111" (add (3,4) == 7)

add2 ("1011","0100") result : "00001" (add2 (-5,4) == 1)add2 ("0011","100") result : "11111" (add2 (3,-4) == -1)

sub ("1011","0100")result : "00111" (sub (11,4) == 7)sub ("0011","100") result : "11111" (sub(3,4) == 31)

Page 342: PrecisionRTL Style

Precision Synthesis Style Guide, 2011a Update2342

Exemplar VHDL PackageThe Exemplar Packages

November 2011

Same as add2, but the subtraction function is implemented on 2-complement representationvectors. op_r is subtracted from op_1.

extend (op_l: std_logic_vector; op_r: integer)return std_logic_vector;

Takes a vector op_l and an integer op_r and returns a vector. The vector op_l is extended in sizeup to op_r elements. The input vector op_l is zero-extended on the MSB side. The left most bitin the vector is assumed the MSB. There is also a version of extend that takes a single(std_logic) value and extends it to a vector of size op_r.

extend2 (op_l: std_logic_vector; op_r: integer)return std_logic_vector;

Same as extend, but the vector is in 2’s-complement representation. The input vector is sign-bitextended. There is also a version of extend2 that takes a single (std_logic) value and sign-extends it to a vector of size op_r.

comp2(op: std_logic_vector)return std_logic_vector;

Takes a vector and returns a vector of the same size. This function assumes the input vector tobe in 2-complement representation and will return the complement (negative) value of the inputvalue. The right most bit is assumed to be the LSB.

"+" (op_l, op_r: std_logic_vector) return std_logic_vector;

Takes two vectors and returns a vector. As add, but now the carry bit is not saved. The resultingvector is the same size as the largest input vector. Overflow wraps around. This functionimplements addition of unsigned vectors.

sub2 ("1011","0100") result : "10111" (sub2(-5,4) == -9)sub2 ("1011", "100") result : "11111" (sub2(-5,-4) == -1)

extend ("1001",7) result : "001001"extend (’1’,3) result : "001"extend ("011001001", 4)result : "1001" -- Truncation

extend2 ("1001",7) result : "1111001"extend2 (’1’,3) result : "111"extend2 ("011001001",4) result : "1001" -- Truncation

comp2 ("1001") result : "0111" ( comp2 (-7) == 7)

"10110" + "101"result : "11011" (22 + 5 == 27)

Page 343: PrecisionRTL Style

Exemplar VHDL PackageThe Exemplar Packages

Precision Synthesis Style Guide, 2011a Update2 343November 2011

"-" (op_l, op_r: std_logic_vector) return std_logic_vector;

Same as “+”, only the subtraction function is performed. op_r is subtracted from op_l. Thisfunction implements subtraction of unsigned vectors.

"mult" (op_l, op_r: std_ulogic_vector) return std_ulogic_vector;

Takes two vectors and returns a vector. The size of the resulting vector is the size of both inputvectors added. In each vector, the left most bit is the MSB. The mult function performsUNSIGNED multiplication of the two input vectors. In case of unequal-length input vectors, thesmallest vector is zero-extended on the MSB side to the size of the largest input vector beforethe multiplication is performed.

"mult2" (op_l, op_r: std_ulogic_vector) return std_ulogic_vector;

Like mult, but now the vectors are assumed to be in 2-complement representation. The sign bitis the left most bit in each vector. In case of unequal-length input vectors, the smallest vector issign-bit extended on the MSB side to the size of the largest input vector before themultiplication is performed.

Predefined ProceduresThere are various ways to generate flip-flops and d-latches with VHDL, such as using processesand specifying behavior that represents the behavior of flip-flops and dlatches. However, insome cases it is useful to instantiate technology independent flip-flops or dlatches in the VHDLdataflow environment immediately.

A more structural oriented VHDL style will be possible that way. The exemplar packageincludes the definition of procedures that represent flip-flops or dlatches with various set orreset facilities that operate on single bits or vectors (to create registers).

The exemplar package defines these procedures on signals of type bit, bit_vector, elbitand elbit_vector, while the package exemplar_1164 defines the same procedures for theIEEE 1164 types std_logic, std_ulogic, std_logic_vector and std_ulogic_vector. Inthe description below only examples for bit and bit_vector are given, but the full definitionof the procedures, for the types listed above, is available for simulation purposes in the filesexemplar.vhd and ex_1164.vhd.

"10110" - "101"result : "10001" (22 - 5 == 17)

mult ("1011", "0100") result: "00101100" (mult(11,4)==44)mult ("1", "1111") result: "00001111" (mult(1,15)==15)

Page 344: PrecisionRTL Style

Precision Synthesis Style Guide, 2011a Update2344

Exemplar VHDL PackageThe Exemplar Packages

November 2011

Flip—flops

Here dff is the single bit D flip-flop and dff_v is the vectored D flip-flop. dff has no preset orclear inputs, dffc has an active-high asynchronous clear (set q to ’0’) input, dffp has anactive-high asynchronous preset (set q to ’1’) input, and dffpc has both a preset and a clearinput. If both preset and clear are asserted, q is not defined. All inputs are active high, the clockinput is positive edge triggered. For the vectored dffs, the number of flip-flops that will beinstantiated is defined by the size of the input (d) and output (q) vectors of the dff#_v

instantiation. (The size of d and q vectors must be the same.)

If q is a port of the VHDL entity, it must be declared as an INOUT port, since q is usedbidirectionally in each of these functions.

Latches

These define a level sensitive D-type latch with an enable. The latch is enabled (transparent)when the enable input is 1, disabled when the input is 0. dlatch has no preset or clearcapability, dlatchc has an asynchronous active-high clear (set q to ’0’) input, dlatchp has anasynchronous active-high preset (set q to ’1’), and dlatchpc has both preset and clear. If bothpreset and clear are asserted, q is not defined. dlatch_v creates the vector equivalentprocedures to generate registers of dlatches.

Tristate BusesWhen a signal is assigned in multiple concurrent statements, the synthesis implementationrequires that in each statement the signal is assigned a ’Z’ value under at least one condition. Atristate gate is created in this case, with the enable of the gate corresponding to the inverse of thecondition where the ’Z’ is assigned in the model. This is the only case where multipleassignments to a signal in different concurrent statements is allowed.

It is also possible for the user to specify what to do in the case where none of the drivers of thebus are enabled. To address this situation, three pre-defined procedures have been declared tohandle the three standard tristate bus conditions: PULLUP, PULLDN and TRSTMEM. These drive anotherwise undriven bus to the values 1, 0, or retain the current value, respectively. Onlyone of these functions may be specified for a given bus. Precision RTL Synthesis will build the

dff[_v](data, clock, q)dffc[_v](data, clear, clock, q)dffp[_v](data, preset, clock, q)dffpc[_v](data, preset, clear, clock, q)

dlatch[_v](data, enable, q)dlatchc[_v](data, clear, enable, q)dlatchp[_v](data, preset, enable, q)dlatchpc[_v](data, preset, clear, enable, q)

Page 345: PrecisionRTL Style

Exemplar VHDL PackageInterfacing With Other VHDL Tools

Precision Synthesis Style Guide, 2011a Update2 345November 2011

appropriate logic to implement the specified function in the technology. If the technologyincludes pull-up or pull-down resistors or repeater cells on internal buses these will be used. Ifthese resistors are not available, an additional tristate gate, with an enable which is the NOR of allthe other enable. The tristate gate input is either VCC, GND or the value on the bus is created toimplement the specified function. Precision RTL Synthesis also determines what the defaultstate for a bus is in the technology. If the default matches the specified function, no extra logic iscreated. If no termination is specified, then the undriven tristate value depends on thetechnology used.

The tristate bus procedures defined below may be used with signals of type bit, elbit,(package exemplar) std_logic and std_ulogic (package exemplar_1164).

pullup (busname)

When a bus is not driven, this procedure pulls the bus up to 1.

pulldn (busname)

When a bus is not driven, this procedure pulls the bus down to 0.

trstmem (busname)

When a bus is not driven, this procedure drives the bus to the last driven state.

Interfacing With Other VHDL ToolsThe VHDL parsers in Precision RTL Synthesis are compliant with the IEEE VHDL 1076-1987standard. Hence, apart from the VHDL restrictions for synthesis, interfacing with tools thatgenerate VHDL or operate on VHDL should not introduce compatibility problems.

However, since VHDL 1076 does not define file handling, there might be mismatches in theway the tools handle files. Many VHDL simulators incorporate a directory structure to storeseparately compiled VHDL files. Precision RTL Synthesis does not use separate compilation ofVHDL files. Therefore, all packages and components that are used for a VHDL designdescription should be identified before running Precision RTL Synthesis, as explained in theprevious section.

Performing Post-layout Functional SimulationYou should always load the packages and entities in your design into the simulator prior tosimulating the root entity. For simulation, the exemplar and exemplar_1164 packages can befound in the <precision install directory>/pkgs/techdata/vhdl directory. The files arenamed exemplar.vhd and ex_1164.vhd, respectively. Refer to the topic The ExemplarPackages for more information on these packages.

Page 346: PrecisionRTL Style

Precision Synthesis Style Guide, 2011a Update2346

Exemplar VHDL PackageWorking with the Synopsys Package

November 2011

If you desire, a post-synthesis functional simulation can be performed using the structuralVHDL output from Precision RTL Synthesis. In your design flow, you should choose theappropriate netlist output for the target technology.

Working with the Synopsys PackageUsers that have existing VHDL files for Synopsys VHDL Compiler can rely on one or more ofthe Synopsys pre-defined VHDL packages. Precision RTL Synthesis supports all thesepackages; a use clause includes the packages in your design.

The Synopsys packages define a set of types and functions that contain Synopsys pragmas thatVHDL Compiler uses as synthesis directives. These pragmas are correctly interpreted by thePrecision Synthesis tools:

pragma translate_onpragma translate_offsynopsys translate _onsynopsys translate_offsynopsys synthesis_onsynopsys synthesis_off

Except for a use clause for each Synopsys package that you need in your VHDL file, youshould not have to load any Synopsys package into Precision RTL Synthesis. Precision RTLSynthesis locates the packages that you want to use in the directory <precision install

directory>/pkgs/techdata/vhdl. Here is the list of files with the contained packages:

Note: Precision RTL Synthesis locates the packages (from the use clause in your VHDLdescription). Precision RTL Synthesis loads any of the listed files from the <precision

install directory>/pkgs/techdata/vhdl directory, or reads a file without the synthesisdirectives. However, without the synthesis directives, Precision RTL Synthesis cannotefficiently synthesize any of the Synopsys packages.

Precision RTL Synthesis assumes that the Synopsys libraries are called from either the VHDLlibrary SYNOPSYS or the VHDL library IEEE.

File Name Package Name

syn_ari.vhd ARITHMETIC

syn_attr.vhd ATTRIBUTES

syn_type.vhd TYPES

syn_arit.vhd STD_LOGIC_ARITH

syn_misc.vhd STD_LOGIC_MISC

syn_unsi.vhd STD_LOGIC_UNSIGNED

syn_sign.vhd STD_LOGIC_SIGNED

Page 347: PrecisionRTL Style

Exemplar VHDL PackageWorking with the Synopsys Package

Precision Synthesis Style Guide, 2011a Update2 347November 2011

NoteThe VHDL library IEEE is a storage recommended by Synopsys.

If you store your Synopsys library (on your VHDL simulator) somewhere else than in theselibraries, then you have to manually include the (package) files needed from the <precision

install directory>/pkgs/techdata/vhdl directory. Precision RTL Synthesis does notrecognize the libraries as Synopsys packages.

• Manually include these packages with the batch mode option -

vhdl_file=libname::filename in the appropriate library.

Use the analyze libname filename interactive command line shell option and argument. Makesure again that you use the files from the <precision install

directory>/pkgs/techdata/vhdl directory (with synthesis directive attributes).

Page 348: PrecisionRTL Style

Precision Synthesis Style Guide, 2011a Update2348

Exemplar VHDL PackageWorking with the Synopsys Package

November 2011

Page 349: PrecisionRTL Style

349

A B F GDC E H I J K L M N O P Q R S T U V XW Y Z

Precision Synthesis Style Guide, 2011a Update2November 2011

— Numerics —2004c Compile Mode, 316

— A —alias, 61Array types

VHDLarray types as scalar, 23constrained array types, 31enumerated-index array types, 28IEEE 1164 array types, 43pre-defined operators, 44syntax and semantics, 26synthesis issues, 28type conversions, 31unconstrained array types, 27

Assignment statementsin VHDL, 39signal, 39variable, 39

Attributesdedicated_mult, 315disable_fsm, 295Exemplar predefined attributes, 45fsm_implementation, 295fsm_state, 295, 296in VHDL source code, 44type_encoding, 296type_encoding_style, 296user-defined attributes, 45VHDL predefined attributes, 45

— B —block statement, 47bus class, 53

— C —Cascaded clocks - conversion, 238case statements

automatic full case detection, 99automatic parallel case detection, 99

casex statement, 100casez statement, 100multiplexer generation, 98Verilog case statement, 96VHDL case statement, 36

component instantiation, 53components

declared, 54structure module, 53

conditional statement, 36configuration declaration, 17continuous assignment

net declaration assignment, 83statement, 84

— D —Data types

SystemVerilog, 130Verilog

net data type, 81parameter data type, 82register data type, 82WAND and WOR net types, 82

Dataflow Environmentoperators, 16statements, 16

design root, 17directives

parallel_case and full_case, 109translate_off and translate_on, 109

disable statement, 102disable_fsm attribute, 295DSP

2004c Compile Mode, 316attributes, 319dedicated_mult attribute, 315, 316, 319frontend_dissolve attribute, 319guidelines, 315inference, 315, 316instantiation, 316, 332

Index

Page 350: PrecisionRTL Style

350November 2011

Precision Synthesis Style Guide, 2011a Update2

A B F GDC E H I J K L M N O P Q R S T U V XW Y Z

Mult-Acc, 325Mult-Acc-AddSub, 327Mult-Add, 321Mult-AddSub, 323multipliers, 316pipelined 35x18 multiplier, 329reset handling, 315, 317use_resource attribute, 319

— E —Entity and package

usage, 60enumerated type, 23Enumerated types, 23, 28, 29Exemplar package

description, 337predefined attributes, 338predefined functions, 339predefined procedures, 343predefined types, 338

— F —Finding definition of component, 58Flip-flops

asynchronous set and reset, 205clock enable, 206predefined procedure, 344synchronous set and reset, 205

Floating-point typesas a scalar in VHDL, 23operator overloading, 44synthesis resolution, 25type conversion in VHDL, 31VHDL, 25VHDL semantics, 25

for loopsSystemVerilog, 141Verilog, 101VHDL, 37

fsm_implementation attribute, 295fsm_state attribute, 295, 296Functions

in Verilog, 104in VHDL, 48

— G —Gated Clock Conversion

AND, 234cascaded clocks, 238NAND, 235NOR, 237OR, 236

generate statement, 37generic

size, 35Generics

generic list, 35

— I —IEEE 1076, 32IEEE 1076-1987, 17IEEE 1076-1993, 17IEEE 1164, 32IEEE 1164 standard logic, 43IEEE 1364, see Verilogif-else statement, 95integer types

VHDLand arithmetic behavior, 23arithmetic operators, 42integer pre-defined type, 24integer range limits, 24integer type example, 31related types, 31syntax, 23synthesis encoding of integer types, 26synthesis issues, 24

— L —Latches, 207Literal values, 128Literals

VHDLconstant values, 21defined, 21

Loop variablesVHDL, 35

— M —Module instantiation

parameter overrides, 89

Page 351: PrecisionRTL Style

351Precision Synthesis Style Guide, 2011a Update2November 2011

A B F GDC E H I J K L M N O P Q R S T U V XW Y Z

— N —Net data types

supply net, 82Verilog WAND and WOR, 82wire and tri net, 82

Numbers, 79

— O —objects

array, 27array naming, 28declared, 22elements, 29enumeration type, 23generic, 35loop variable, 35physical type, 26port, 34ports, 34record, 29signal, 33variable, 34, 207

operand, 90Operators

IEEE 1076 pre-defined, 41Verilog

arithmetic operator, 91bit-wise operator, 93concatenation, 94conditional operator, 93logical operator, 92reduction operator, 93relational and equality operator, 92shift operator, 93signed and unsigned attribute, 94

VHDLarithmetic, 28, 42concatenation, 42exemplar package, 28exemplar_1164 package, 28logical, 41, 42overloading, 22, 44pre-defined, 41relational, 41vector arithmetics, 42

— P —package

body, 59header, 59

Packages, 59Partitioning

blocks, 47processes, 47

Physical types, 23, 26Ports

VHDLport statement, 34

Post-layout functional simulation, 345Pragmas

Verilog, 109procedure statement, 48Processes, 19

— R —Record types, 23, 29Registers

AND gated clock, 234cascaded clocks, 238NAND gated clock, 235NOR gated clock, 237OR gated clock, 236

Resolution functions, 50

— S —Signals, 33Signed attribute

on operators, 94Statements

VHDLassignment statement, 39basic statements, 35conditional statement, 36generate statement, 37loop statement, 37loop variable, 35selection statement, 36

std_logic, 33, 42, 50, 51Subprograms

function, 48procedure, 48

Subtypes, 30, 31

Page 352: PrecisionRTL Style

352November 2011

Precision Synthesis Style Guide, 2011a Update2

A B F GDC E H I J K L M N O P Q R S T U V XW Y Z

Synopsys integration and packages, 346Syntax and semantic restrictions, 62

synthesis tool restrictions, 62VHDL language Restriction, 63

Synthesis directivesattribute, 109translate_off and translate_on, 109

SystemVerilog, 119’define macro, 150always_comb, 143always_latch, 144always_seq, 144argument passing by name, 146array assignment, 137array literals, 130array type literal, 128array types, 135arrays as arguments, 138assignment operators, 139attributes, 139break, 141compiler directives, 150constants, 138continue, 141data types, 130

casting, 135enumerations, 134integer types, 132structures, 134unions, 134user defined types, 133

do...while loop, 140example designs, 152for loops, 141function, 145implicit .* port connections, 148implicit .name port connections, 147indexing arrays, 136integer and logic literals, 129integer type, 128interfaces, 148language features, 119literal values, 128logic type, 128multi-dimensioned arrays, 136

named blocks, 143packed arrays, 135port declarations, 147processes, 143real literals, 129real type, 128return, 141return expression, 141selection statements, 139slicing arrays, 136string literals, 130string of type packed array, 128structure literals, 128task, 145tasks and functions, 145Time literal, 128unpacked arrays, 135void functions, 146

— T —Tasks, 105type_encoding attribute, 296type_encoding_style attribute, 296Types

array types, 26enumeration type, 23floating-point type, 25IEEE 1076 predefined type, 32IEEE 1076 predefined types, 32IEEE 1164, 33integer type, 23physical type, 26record type, 29subtypes, 30type conversions, 31

— U —Unsigned attribute

on operators, 94

— V —variable statement, 207Verilog

if-else statement, 95parameter data type, 82pragmas, 109

Page 353: PrecisionRTL Style

353Precision Synthesis Style Guide, 2011a Update2November 2011

A B F GDC E H I J K L M N O P Q R S T U V XW Y Z

register data type, 82signed and unsigned attributes, 94

Verilog 2001 Support, 111VHDL

architectures, 16array types, 23basic statements, 35blocks, 47dataflow environment, 16entities, 16enumerated-index array types, 28environment

interfacing with other VHDL tools, 345IEEE 1076-1987, 17IEEE 1076-1993, 17integer type, 23loop variables, 35object

signal, 16package handling, 17procedure statement, 48variable statement, 207

void, 146

— W —while loop, 37

Page 354: PrecisionRTL Style

354November 2011

Precision Synthesis Style Guide, 2011a Update2

A B F GDC E H I J K L M N O P Q R S T U V XW Y Z

Page 355: PrecisionRTL Style

End-User License AgreementThe latest version of the End-User License Agreement is available on-line at:

www.mentor.com/eula

END-USER LICENSE AGREEMENT (“Agreement”)

This is a legal agreement concerning the use of Software (as defined in Section 2) and hardware (collectively“Products”) between the company acquiring the Products (“Customer”), and the Mentor Graphics entity thatissued the corresponding quotation or, if no quotation was issued, the applicable local Mentor Graphics entity(“Mentor Graphics”). Except for license agreements related to the subject matter of this license agreement whichare physically signed by Customer and an authorized representative of Mentor Graphics, this Agreement and theapplicable quotation contain the parties' entire understanding relating to the subject matter and supersede allprior or contemporaneous agreements. If Customer does not agree to these terms and conditions, promptly returnor, in the case of Software received electronically, certify destruction of Software and all accompanying itemswithin five days after receipt of Software and receive a full refund of any license fee paid.

1. ORDERS, FEES AND PAYMENT.

1.1. To the extent Customer (or if agreed by Mentor Graphics, Customer’s appointed third party buying agent) places andMentor Graphics accepts purchase orders pursuant to this Agreement (“Order(s)”), each Order will constitute a contractbetween Customer and Mentor Graphics, which shall be governed solely and exclusively by the terms and conditions of thisAgreement, any applicable addenda and the applicable quotation, whether or not these documents are referenced on theOrder. Any additional or conflicting terms and conditions appearing on an Order will not be effective unless agreed inwriting by an authorized representative of Customer and Mentor Graphics.

1.2. Amounts invoiced will be paid, in the currency specified on the applicable invoice, within 30 days from the date of suchinvoice. Any past due invoices will be subject to the imposition of interest charges in the amount of one and one-halfpercent per month or the applicable legal rate currently in effect, whichever is lower. Prices do not include freight,insurance, customs duties, taxes or other similar charges, which Mentor Graphics will state separately in the applicableinvoice(s). Unless timely provided with a valid certificate of exemption or other evidence that items are not taxable, MentorGraphics will invoice Customer for all applicable taxes including, but not limited to, VAT, GST, sales tax and service tax.Customer will make all payments free and clear of, and without reduction for, any withholding or other taxes; any suchtaxes imposed on payments by Customer hereunder will be Customer’s sole responsibility. If Customer appoints a thirdparty to place purchase orders and/or make payments on Customer’s behalf, Customer shall be liable for payment underOrders placed by such third party in the event of default.

1.3. All Products are delivered FCA factory (Incoterms 2000), freight prepaid and invoiced to Customer, except Softwaredelivered electronically, which shall be deemed delivered when made available to Customer for download. MentorGraphics retains a security interest in all Products delivered under this Agreement, to secure payment of the purchase priceof such Products, and Customer agrees to sign any documents that Mentor Graphics determines to be necessary orconvenient for use in filing or perfecting such security interest. Mentor Graphics’ delivery of Software by electronic meansis subject to Customer’s provision of both a primary and an alternate e-mail address.

2. GRANT OF LICENSE. The software installed, downloaded, or otherwise acquired by Customer under this Agreement,including any updates, modifications, revisions, copies, documentation and design data (“Software”) are copyrighted, tradesecret and confidential information of Mentor Graphics or its licensors, who maintain exclusive title to all Software and retainall rights not expressly granted by this Agreement. Mentor Graphics grants to Customer, subject to payment of applicablelicense fees, a nontransferable, nonexclusive license to use Software solely: (a) in machine-readable, object-code form (exceptas provided in Subsection 5.2); (b) for Customer’s internal business purposes; (c) for the term of the license; and (d) on thecomputer hardware and at the site authorized by Mentor Graphics. A site is restricted to a one-half mile (800 meter) radius.Customer may have Software temporarily used by an employee for telecommuting purposes from locations other than aCustomer office, such as the employee's residence, an airport or hotel, provided that such employee's primary place ofemployment is the site where the Software is authorized for use. Mentor Graphics’ standard policies and programs, which varydepending on Software, license fees paid or services purchased, apply to the following: (a) relocation of Software; (b) use ofSoftware, which may be limited, for example, to execution of a single session by a single user on the authorized hardware or fora restricted period of time (such limitations may be technically implemented through the use of authorization codes or similardevices); and (c) support services provided, including eligibility to receive telephone support, updates, modifications, andrevisions. For the avoidance of doubt, if Customer requests any change or enhancement to Software, whether in the course of

IMPORTANT INFORMATION

USE OF ALL SOFTWARE IS SUBJECT TO LICENSE RESTRICTIONS. CAREFULLY READ THISLICENSE AGREEMENT BEFORE USING THE PRODUCTS. USE OF SOFTWARE INDICATES

CUSTOMER’S COMPLETE AND UNCONDITIONAL ACCEPTANCE OF THE TERMS ANDCONDITIONS SET FORTH IN THIS AGREEMENT. ANY ADDITIONAL OR DIFFERENT PURCHASE

ORDER TERMS AND CONDITIONS SHALL NOT APPLY.

Page 356: PrecisionRTL Style

receiving support or consulting services, evaluating Software, performing beta testing or otherwise, any inventions, productimprovements, modifications or developments made by Mentor Graphics (at Mentor Graphics’ sole discretion) will be theexclusive property of Mentor Graphics.

3. ESC SOFTWARE. If Customer purchases a license to use development or prototyping tools of Mentor Graphics’ EmbeddedSoftware Channel (“ESC”), Mentor Graphics grants to Customer a nontransferable, nonexclusive license to reproduce anddistribute executable files created using ESC compilers, including the ESC run-time libraries distributed with ESC C and C++compiler Software that are linked into a composite program as an integral part of Customer’s compiled computer program,provided that Customer distributes these files only in conjunction with Customer’s compiled computer program. MentorGraphics does NOT grant Customer any right to duplicate, incorporate or embed copies of Mentor Graphics’ real-time operatingsystems or other embedded software products into Customer’s products or applications without first signing or otherwiseagreeing to a separate agreement with Mentor Graphics for such purpose.

4. BETA CODE.

4.1. Portions or all of certain Software may contain code for experimental testing and evaluation (“Beta Code”), which may notbe used without Mentor Graphics’ explicit authorization. Upon Mentor Graphics’ authorization, Mentor Graphics grants toCustomer a temporary, nontransferable, nonexclusive license for experimental use to test and evaluate the Beta Codewithout charge for a limited period of time specified by Mentor Graphics. This grant and Customer’s use of the Beta Codeshall not be construed as marketing or offering to sell a license to the Beta Code, which Mentor Graphics may choose not torelease commercially in any form.

4.2. If Mentor Graphics authorizes Customer to use the Beta Code, Customer agrees to evaluate and test the Beta Code undernormal conditions as directed by Mentor Graphics. Customer will contact Mentor Graphics periodically during Customer’suse of the Beta Code to discuss any malfunctions or suggested improvements. Upon completion of Customer’s evaluationand testing, Customer will send to Mentor Graphics a written evaluation of the Beta Code, including its strengths,weaknesses and recommended improvements.

4.3. Customer agrees to maintain Beta Code in confidence and shall restrict access to the Beta Code, including the methods andconcepts utilized therein, solely to those employees and Customer location(s) authorized by Mentor Graphics to performbeta testing. Customer agrees that any written evaluations and all inventions, product improvements, modifications ordevelopments that Mentor Graphics conceived or made during or subsequent to this Agreement, including those basedpartly or wholly on Customer’s feedback, will be the exclusive property of Mentor Graphics. Mentor Graphics will haveexclusive rights, title and interest in all such property. The provisions of this Subsection 4.3 shall survive termination of thisAgreement.

5. RESTRICTIONS ON USE.

5.1. Customer may copy Software only as reasonably necessary to support the authorized use. Each copy must include allnotices and legends embedded in Software and affixed to its medium and container as received from Mentor Graphics. Allcopies shall remain the property of Mentor Graphics or its licensors. Customer shall maintain a record of the number andprimary location of all copies of Software, including copies merged with other software, and shall make those recordsavailable to Mentor Graphics upon request. Customer shall not make Products available in any form to any person otherthan Customer’s employees and on-site contractors, excluding Mentor Graphics competitors, whose job performancerequires access and who are under obligations of confidentiality. Customer shall take appropriate action to protect theconfidentiality of Products and ensure that any person permitted access does not disclose or use it except as permitted bythis Agreement. Customer shall give Mentor Graphics written notice of any unauthorized disclosure or use of the Productsas soon as Customer learns or becomes aware of such unauthorized disclosure or use. Except as otherwise permitted forpurposes of interoperability as specified by applicable and mandatory local law, Customer shall not reverse-assemble,reverse-compile, reverse-engineer or in any way derive any source code from Software. Log files, data files, rule files andscript files generated by or for the Software (collectively “Files”), including without limitation files containing StandardVerification Rule Format (“SVRF”) and Tcl Verification Format (“TVF”) which are Mentor Graphics’ proprietary syntaxesfor expressing process rules, constitute or include confidential information of Mentor Graphics. Customer may share Fileswith third parties, excluding Mentor Graphics competitors, provided that the confidentiality of such Files is protected bywritten agreement at least as well as Customer protects other information of a similar nature or importance, but in any casewith at least reasonable care. Customer may use Files containing SVRF or TVF only with Mentor Graphics products. Underno circumstances shall Customer use Software or Files or allow their use for the purpose of developing, enhancing ormarketing any product that is in any way competitive with Software, or disclose to any third party the results of, orinformation pertaining to, any benchmark.

5.2. If any Software or portions thereof are provided in source code form, Customer will use the source code only to correctsoftware errors and enhance or modify the Software for the authorized use. Customer shall not disclose or permit disclosureof source code, in whole or in part, including any of its methods or concepts, to anyone except Customer’s employees orcontractors, excluding Mentor Graphics competitors, with a need to know. Customer shall not copy or compile source codein any manner except to support this authorized use.

5.3. Customer may not assign this Agreement or the rights and duties under it, or relocate, sublicense or otherwise transfer theProducts, whether by operation of law or otherwise (“Attempted Transfer”), without Mentor Graphics’ prior writtenconsent and payment of Mentor Graphics’ then-current applicable relocation and/or transfer fees. Any Attempted Transferwithout Mentor Graphics’ prior written consent shall be a material breach of this Agreement and may, at Mentor Graphics’option, result in the immediate termination of the Agreement and/or the licenses granted under this Agreement. The terms

Page 357: PrecisionRTL Style

of this Agreement, including without limitation the licensing and assignment provisions, shall be binding upon Customer’spermitted successors in interest and assigns.

5.4. The provisions of this Section 5 shall survive the termination of this Agreement.

6. SUPPORT SERVICES. To the extent Customer purchases support services, Mentor Graphics will provide Customer updatesand technical support for the Products, at the Customer site(s) for which support is purchased, in accordance with MentorGraphics’ then current End-User Support Terms located at http://supportnet.mentor.com/about/legal/.

7. AUTOMATIC CHECK FOR UPDATES; PRIVACY. Technological measures in Software may communicate with serversof Mentor Graphics or its contractors for the purpose of checking for and notifying the user of updates and to ensure that theSoftware in use is licensed in compliance with this Agreement. Mentor Graphics will not collect any personally identifiable datain this process and will not disclose any data collected to any third party without the prior written consent of Customer, except toMentor Graphics’ outside attorneys or as may be required by a court of competent jurisdiction.

8. LIMITED WARRANTY.

8.1. Mentor Graphics warrants that during the warranty period its standard, generally supported Products, when properlyinstalled, will substantially conform to the functional specifications set forth in the applicable user manual. MentorGraphics does not warrant that Products will meet Customer’s requirements or that operation of Products will beuninterrupted or error free. The warranty period is 90 days starting on the 15th day after delivery or upon installation,whichever first occurs. Customer must notify Mentor Graphics in writing of any nonconformity within the warranty period.For the avoidance of doubt, this warranty applies only to the initial shipment of Software under an Order and does notrenew or reset, for example, with the delivery of (a) Software updates or (b) authorization codes or alternate Software undera transaction involving Software re-mix. This warranty shall not be valid if Products have been subject to misuse,unauthorized modification or improper installation. MENTOR GRAPHICS’ ENTIRE LIABILITY AND CUSTOMER’SEXCLUSIVE REMEDY SHALL BE, AT MENTOR GRAPHICS’ OPTION, EITHER (A) REFUND OF THE PRICEPAID UPON RETURN OF THE PRODUCTS TO MENTOR GRAPHICS OR (B) MODIFICATION ORREPLACEMENT OF THE PRODUCTS THAT DO NOT MEET THIS LIMITED WARRANTY, PROVIDEDCUSTOMER HAS OTHERWISE COMPLIED WITH THIS AGREEMENT. MENTOR GRAPHICS MAKES NOWARRANTIES WITH RESPECT TO: (A) SERVICES; (B) PRODUCTS PROVIDED AT NO CHARGE; OR (C) BETACODE; ALL OF WHICH ARE PROVIDED “AS IS.”

8.2. THE WARRANTIES SET FORTH IN THIS SECTION 8 ARE EXCLUSIVE. NEITHER MENTOR GRAPHICS NORITS LICENSORS MAKE ANY OTHER WARRANTIES EXPRESS, IMPLIED OR STATUTORY, WITH RESPECT TOPRODUCTS PROVIDED UNDER THIS AGREEMENT. MENTOR GRAPHICS AND ITS LICENSORSSPECIFICALLY DISCLAIM ALL IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR APARTICULAR PURPOSE AND NON-INFRINGEMENT OF INTELLECTUAL PROPERTY.

9. LIMITATION OF LIABILITY. EXCEPT WHERE THIS EXCLUSION OR RESTRICTION OF LIABILITY WOULD BEVOID OR INEFFECTIVE UNDER APPLICABLE LAW, IN NO EVENT SHALL MENTOR GRAPHICS OR ITSLICENSORS BE LIABLE FOR INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES (INCLUDINGLOST PROFITS OR SAVINGS) WHETHER BASED ON CONTRACT, TORT OR ANY OTHER LEGAL THEORY, EVENIF MENTOR GRAPHICS OR ITS LICENSORS HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. INNO EVENT SHALL MENTOR GRAPHICS’ OR ITS LICENSORS’ LIABILITY UNDER THIS AGREEMENT EXCEEDTHE AMOUNT RECEIVED FROM CUSTOMER FOR THE HARDWARE, SOFTWARE LICENSE OR SERVICE GIVINGRISE TO THE CLAIM. IN THE CASE WHERE NO AMOUNT WAS PAID, MENTOR GRAPHICS AND ITS LICENSORSSHALL HAVE NO LIABILITY FOR ANY DAMAGES WHATSOEVER. THE PROVISIONS OF THIS SECTION 9 SHALLSURVIVE THE TERMINATION OF THIS AGREEMENT.

10. HAZARDOUS APPLICATIONS. CUSTOMER ACKNOWLEDGES IT IS SOLELY RESPONSIBLE FOR TESTING ITSPRODUCTS USED IN APPLICATIONS WHERE THE FAILURE OR INACCURACY OF ITS PRODUCTS MIGHTRESULT IN DEATH OR PERSONAL INJURY (“HAZARDOUS APPLICATIONS”). NEITHER MENTOR GRAPHICSNOR ITS LICENSORS SHALL BE LIABLE FOR ANY DAMAGES RESULTING FROM OR IN CONNECTION WITHTHE USE OF MENTOR GRAPHICS PRODUCTS IN OR FOR HAZARDOUS APPLICATIONS. THE PROVISIONS OFTHIS SECTION 10 SHALL SURVIVE THE TERMINATION OF THIS AGREEMENT.

11. INDEMNIFICATION. CUSTOMER AGREES TO INDEMNIFY AND HOLD HARMLESS MENTOR GRAPHICS ANDITS LICENSORS FROM ANY CLAIMS, LOSS, COST, DAMAGE, EXPENSE OR LIABILITY, INCLUDINGATTORNEYS’ FEES, ARISING OUT OF OR IN CONNECTION WITH THE USE OF PRODUCTS AS DESCRIBED INSECTION 10. THE PROVISIONS OF THIS SECTION 11 SHALL SURVIVE THE TERMINATION OF THISAGREEMENT.

12. INFRINGEMENT.

12.1. Mentor Graphics will defend or settle, at its option and expense, any action brought against Customer in the United States,Canada, Japan, or member state of the European Union which alleges that any standard, generally supported Productacquired by Customer hereunder infringes a patent or copyright or misappropriates a trade secret in such jurisdiction.Mentor Graphics will pay costs and damages finally awarded against Customer that are attributable to the action. Customerunderstands and agrees that as conditions to Mentor Graphics’ obligations under this section Customer must: (a) notifyMentor Graphics promptly in writing of the action; (b) provide Mentor Graphics all reasonable information and assistance

Page 358: PrecisionRTL Style

to settle or defend the action; and (c) grant Mentor Graphics sole authority and control of the defense or settlement of theaction.

12.2. If a claim is made under Subsection 12.1 Mentor Graphics may, at its option and expense, (a) replace or modify the Productso that it becomes noninfringing; (b) procure for Customer the right to continue using the Product; or (c) require the returnof the Product and refund to Customer any purchase price or license fee paid, less a reasonable allowance for use.

12.3. Mentor Graphics has no liability to Customer if the action is based upon: (a) the combination of Software or hardware withany product not furnished by Mentor Graphics; (b) the modification of the Product other than by Mentor Graphics; (c) theuse of other than a current unaltered release of Software; (d) the use of the Product as part of an infringing process; (e) aproduct that Customer makes, uses, or sells; (f) any Beta Code or Product provided at no charge; (g) any software providedby Mentor Graphics’ licensors who do not provide such indemnification to Mentor Graphics’ customers; or(h) infringement by Customer that is deemed willful. In the case of (h), Customer shall reimburse Mentor Graphics for itsreasonable attorney fees and other costs related to the action.

12.4. THIS SECTION 12 IS SUBJECT TO SECTION 9 ABOVE AND STATES THE ENTIRE LIABILITY OF MENTORGRAPHICS AND ITS LICENSORS FOR DEFENSE, SETTLEMENT AND DAMAGES, AND CUSTOMER’S SOLEAND EXCLUSIVE REMEDY, WITH RESPECT TO ANY ALLEGED PATENT OR COPYRIGHT INFRINGEMENTOR TRADE SECRET MISAPPROPRIATION BY ANY PRODUCT PROVIDED UNDER THIS AGREEMENT.

13. TERMINATION AND EFFECT OF TERMINATION. If a Software license was provided for limited term use, such licensewill automatically terminate at the end of the authorized term.

13.1. Mentor Graphics may terminate this Agreement and/or any license granted under this Agreement immediately upon writtennotice if Customer: (a) exceeds the scope of the license or otherwise fails to comply with the licensing or confidentialityprovisions of this Agreement, or (b) becomes insolvent, files a bankruptcy petition, institutes proceedings for liquidation orwinding up or enters into an agreement to assign its assets for the benefit of creditors. For any other material breach of anyprovision of this Agreement, Mentor Graphics may terminate this Agreement and/or any license granted under thisAgreement upon 30 days written notice if Customer fails to cure the breach within the 30 day notice period. Termination ofthis Agreement or any license granted hereunder will not affect Customer’s obligation to pay for Products shipped orlicenses granted prior to the termination, which amounts shall be payable immediately upon the date of termination.

13.2. Upon termination of this Agreement, the rights and obligations of the parties shall cease except as expressly set forth in thisAgreement. Upon termination, Customer shall ensure that all use of the affected Products ceases, and shall return hardwareand either return to Mentor Graphics or destroy Software in Customer’s possession, including all copies anddocumentation, and certify in writing to Mentor Graphics within ten business days of the termination date that Customer nolonger possesses any of the affected Products or copies of Software in any form.

14. EXPORT. The Products provided hereunder are subject to regulation by local laws and United States government agencies,which prohibit export or diversion of certain products and information about the products to certain countries and certainpersons. Customer agrees that it will not export Products in any manner without first obtaining all necessary approval fromappropriate local and United States government agencies.

15. U.S. GOVERNMENT LICENSE RIGHTS. Software was developed entirely at private expense. All Software is commercialcomputer software within the meaning of the applicable acquisition regulations. Accordingly, pursuant to US FAR 48 CFR12.212 and DFAR 48 CFR 227.7202, use, duplication and disclosure of the Software by or for the U.S. Government or a U.S.Government subcontractor is subject solely to the terms and conditions set forth in this Agreement, except for provisions whichare contrary to applicable mandatory federal laws.

16. THIRD PARTY BENEFICIARY. Mentor Graphics Corporation, Mentor Graphics (Ireland) Limited, Microsoft Corporationand other licensors may be third party beneficiaries of this Agreement with the right to enforce the obligations set forth herein.

17. REVIEW OF LICENSE USAGE. Customer will monitor the access to and use of Software. With prior written notice andduring Customer’s normal business hours, Mentor Graphics may engage an internationally recognized accounting firm toreview Customer’s software monitoring system and records deemed relevant by the internationally recognized accounting firmto confirm Customer’s compliance with the terms of this Agreement or U.S. or other local export laws. Such review may includeFLEXlm or FLEXnet (or successor product) report log files that Customer shall capture and provide at Mentor Graphics’request. Customer shall make records available in electronic format and shall fully cooperate with data gathering to support thelicense review. Mentor Graphics shall bear the expense of any such review unless a material non-compliance is revealed. MentorGraphics shall treat as confidential information all information gained as a result of any request or review and shall only use ordisclose such information as required by law or to enforce its rights under this Agreement. The provisions of this Section 17shall survive the termination of this Agreement.

18. CONTROLLING LAW, JURISDICTION AND DISPUTE RESOLUTION. The owners of certain Mentor Graphicsintellectual property licensed under this Agreement are located in Ireland and the United States. To promote consistency aroundthe world, disputes shall be resolved as follows: excluding conflict of laws rules, this Agreement shall be governed by andconstrued under the laws of the State of Oregon, USA, if Customer is located in North or South America, and the laws of Irelandif Customer is located outside of North or South America. All disputes arising out of or in relation to this Agreement shall besubmitted to the exclusive jurisdiction of the courts of Portland, Oregon when the laws of Oregon apply, or Dublin, Ireland whenthe laws of Ireland apply. Notwithstanding the foregoing, all disputes in Asia arising out of or in relation to this Agreement shallbe resolved by arbitration in Singapore before a single arbitrator to be appointed by the chairman of the Singapore International

Page 359: PrecisionRTL Style

Arbitration Centre (“SIAC”) to be conducted in the English language, in accordance with the Arbitration Rules of the SIAC ineffect at the time of the dispute, which rules are deemed to be incorporated by reference in this section. This section shall notrestrict Mentor Graphics’ right to bring an action against Customer in the jurisdiction where Customer’s place of business islocated. The United Nations Convention on Contracts for the International Sale of Goods does not apply to this Agreement.

19. SEVERABILITY. If any provision of this Agreement is held by a court of competent jurisdiction to be void, invalid,unenforceable or illegal, such provision shall be severed from this Agreement and the remaining provisions will remain in fullforce and effect.

20. MISCELLANEOUS. This Agreement contains the parties’ entire understanding relating to its subject matter and supersedes allprior or contemporaneous agreements, including but not limited to any purchase order terms and conditions. Some Softwaremay contain code distributed under a third party license agreement that may provide additional rights to Customer. Please seethe applicable Software documentation for details. This Agreement may only be modified in writing by authorizedrepresentatives of the parties. Waiver of terms or excuse of breach must be in writing and shall not constitute subsequentconsent, waiver or excuse.

Rev. 100615, Part No. 246066