Model: User's Manual
Model: User's Manual
SE
User’s Manual
Version 6.0b
Published: 15/Nov/04
UM-2
This document is for information and instruction purposes. Mentor Graphics reserves the
right to make changes in specifications and other information contained in this publication
without prior notice, and the reader should, in all cases, consult Mentor Graphics to
determine whether any changes have been made.
The terms and conditions governing the sale and licensing of Mentor Graphics products are
set forth in written agreements between Mentor Graphics and its customers. No
representation or other affirmation of fact contained in this publication shall be deemed to
be a warranty or give rise to any liability of Mentor Graphics whatsoever.
MENTOR GRAPHICS MAKES NO WARRANTY OF ANY KIND WITH REGARD TO
THIS MATERIAL INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OR MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE.
MENTOR GRAPHICS SHALL NOT BE LIABLE FOR ANY INCIDENTAL,
INDIRECT, SPECIAL, OR CONSEQUENTIAL 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 OF SUCH DAMAGES.
RESTRICTED RIGHTS LEGEND 03/97
U.S. Government Restricted Rights. The SOFTWARE and documentation have been
developed entirely at 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 the restrictions 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 - Restricted Rights
clause at FAR 52.227-19, as applicable.
Contractor/manufacturer is:
Mentor Graphics Corporation
8005 S.W. Boeckman Road, Wilsonville, Oregon 97070-7777.
This is an unpublished work of Mentor Graphics Corporation.
Contacting ModelSim Support
Telephone: 503.685.0820
Toll-Free Telephone: 877-744-6699
Website: www.model.com
Support: www.model.com/support
Table of Contents
1 - Introduction (UM-21)
ModelSim tool structure and verification flow . . . . . . . . . . . . . . . . . . . . UM-22
ModelSim simulation task overview . . . . . . . . . . . . . . . . . . . . . . . . UM-23
Basic steps for simulation . . . . . . . . . . . . . . . . . . . . . . . . . . . . UM-24
Step 1 - Collecting Files and Mapping Libraries . . . . . . . . . . . . . . . . . UM-24
Step 2 - Compiling the design with vlog/vcom/sccom . . . . . . . . . . . . . . . UM-25
Step 3 - Loading the design for simulation . . . . . . . . . . . . . . . . . . . UM-26
Step 4 - Simulating the design . . . . . . . . . . . . . . . . . . . . . . . . UM-26
Step 5- Debugging the design . . . . . . . . . . . . . . . . . . . . . . . . . UM-26
ModelSim modes of operation . . . . . . . . . . . . . . . . . . . . . . . . . . UM-27
Command-line mode . . . . . . . . . . . . . . . . . . . . . . . . . . . . UM-27
Batch mode . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . UM-28
ModelSim graphic interface overview . . . . . . . . . . . . . . . . . . . . . . . UM-29
Standards supported . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . UM-30
Assumptions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . UM-30
Sections in this document . . . . . . . . . . . . . . . . . . . . . . . . . . . . UM-31
What is an "object" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . UM-34
Text conventions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . UM-34
Where to find our documentation . . . . . . . . . . . . . . . . . . . . . . . . . UM-35
Download a free PDF reader with Search . . . . . . . . . . . . . . . . . . . . UM-35
Technical support and updates . . . . . . . . . . . . . . . . . . . . . . . . . . UM-36
2 - Projects (UM-37)
Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . UM-38
What are projects? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . UM-38
What are the benefits of projects? . . . . . . . . . . . . . . . . . . . . . . . UM-38
Project conversion between versions . . . . . . . . . . . . . . . . . . . . . . UM-39
Getting started with projects . . . . . . . . . . . . . . . . . . . . . . . . . . . UM-40
Step 1 — Creating a new project . . . . . . . . . . . . . . . . . . . . . . . UM-40
Step 2 — Adding items to the project . . . . . . . . . . . . . . . . . . . . . UM-41
Step 3 — Compiling the files . . . . . . . . . . . . . . . . . . . . . . . . . UM-43
Step 4 — Simulating a design . . . . . . . . . . . . . . . . . . . . . . . . UM-44
Other basic project operations . . . . . . . . . . . . . . . . . . . . . . . . UM-44
The Project tab . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . UM-45
Sorting the list . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . UM-45
Changing compile order . . . . . . . . . . . . . . . . . . . . . . . . . . . . UM-46
Auto-generating compile order . . . . . . . . . . . . . . . . . . . . . . . . UM-46
Grouping files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . UM-47
Creating a Simulation Configuration . . . . . . . . . . . . . . . . . . . . . . . . UM-48
Optimization Configurations . . . . . . . . . . . . . . . . . . . . . . . . . UM-49
16 - C Debug (UM-399)
Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . UM-400
Supported platforms and gdb versions . . . . . . . . . . . . . . . . . . . . . . UM-401
Running C Debug on Windows platforms . . . . . . . . . . . . . . . . . . . UM-401
Setting up C Debug . . . . . . . . . . . . . . . . . . . . . . . . . . . . . UM-402
Running C Debug from a DO file . . . . . . . . . . . . . . . . . . . . . . UM-402
Setting breakpoints . . . . . . . . . . . . . . . . . . . . . . . . . . . . . UM-403
Stepping in C Debug . . . . . . . . . . . . . . . . . . . . . . . . . . . . . UM-405
Known problems with stepping in C Debug . . . . . . . . . . . . . . . . . . UM-405
Finding function entry points with Auto find bp . . . . . . . . . . . . . . . . . . UM-406
Identifying all registered function calls . . . . . . . . . . . . . . . . . . . . . . UM-407
Enabling Auto step mode . . . . . . . . . . . . . . . . . . . . . . . . . UM-407
Example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . UM-408
Auto find bp versus Auto step mode . . . . . . . . . . . . . . . . . . . . . UM-409
Debugging functions during elaboration . . . . . . . . . . . . . . . . . . . . . UM-410
FLI functions in initialization mode . . . . . . . . . . . . . . . . . . . . . UM-411
PLI functions in initialization mode . . . . . . . . . . . . . . . . . . . . . UM-411
VPI functions in initialization mode . . . . . . . . . . . . . . . . . . . . . UM-413
Completing design load . . . . . . . . . . . . . . . . . . . . . . . . . . UM-413
Debugging functions when quitting simulation . . . . . . . . . . . . . . . . . . . UM-414
C Debug command reference . . . . . . . . . . . . . . . . . . . . . . . . . UM-415
Index
1 - Introduction
Chapter contents
ModelSim tool structure and verification flow . . . . . . . UM-22
ModelSim simulation task overview . . . . . . . . . . UM-23
Assumptions . . . . . . . . . . . . . . . . UM-30
This documentation was written for ModelSim for UNIX and Microsoft Windows. Not all
versions of ModelSim are supported on all platforms. Contact your Mentor Graphics sales
representative for details.
VHDL
Design
Libraries vlib
Map libraries
vlog/
Design
files vcom/ HDL/SystemC
sccom Analyze/
Analyze/ Compile
.ini or
.mpf file Compile
vopt OPTIONAL:
Optimize
Verilog
compiled
database
vsim Simulate
Interactive Debugging
activities i.e. Debug
Simulation Output
(e.g., vcd)
Post-processing Debug
Step 2: vlog file1.v file2.v ... (Verilog) a. Compile > Compile Compile or
Compile the vcom file1.vhd file2.vhd ... or Compile All icons:
design (VHDL) Compile > Compile All
Library (see "Creating a library" (UM-60)), or you can use the vlib (CR-356) command. For
example, the command:
vlib work
creates a library named work. By default, compilation results are stored in the work
library.
This command sets the mapping between a logical library name and a directory.
vsim <top>
Your design is ready for simulation after it has been compiled and (optionally) optimized
with vopt (CR-371). For more information on optimization, see Optimizing Verilog
designs (UM-124). You may then invoke vsim (CR-373) with the names of the top-level
modules (many designs contain only one top-level module) or the name you assigned to the
optimized version of the design. For example, if your top-level modules are "testbench" and
"globals", then invoke the simulator as follows:
vsim testbench globals
After the simulator loads the top-level modules, it iteratively loads the instantiated modules
and UDPs in the design hierarchy, linking the design together by connecting the ports and
resolving hierarchical references.
Using SDF
You can incorporate actual delay values to the simulation by applying SDF back-
annotation files to the design. For more information on how SDF is used in the design, see
"Specifying SDF files for simulation" (UM-440).
In addition, several basic simulation commands are available from the command line to
assist you in debugging your design:
describe (CR-147)
drivers (CR-154)
examine (CR-162)
force (CR-180)
log (CR-191)
checkpoint (CR-93)
restore (CR-248)
show (CR-267)
GUI interactive; has graphical via a desktop icon or from the OS command shell
windows, push-buttons, prompt. Example:
menus, and a command line in
the transcript. OS> vsim
Default mode.
Command-line interactive command line; no with -c argument at the OS command prompt. Example:
GUI.
OS> vsim -c
Batch non-interactive batch script; at OS command shell prompt using "here document"
no windows or interactive technique or redirection of standard input. Example:
command line.
C:\ vsim vfiles.v <infile >outfile
The ModelSim User’s Manual focuses primarily on the GUI mode of operation. However,
this section provides an introduction to the Command-line and Batch modes.
Command-line mode
In command-line mode ModelSim executes any startup command specified by the Startup
(UM-534) variable in the modelsim.ini file. If vsim (CR-373) is invoked with the -do
"command_string" option, a DO file (macro) is called. A DO file executed in this manner
will override any startup command in the modelsim.ini file.
During simulation a transcript file is created containing any messages to stdout. A transcript
file created in command-line mode may be used as a DO file if you invoke the transcript
on command (CR-286) after the design loads (see the example below). The transcript on
command writes all of the commands you invoke to the transcript file. For example, the
following series of commands results in a transcript file that can be used for command input
if top is re-simulated (remove the quit -f command from the transcript file if you want to
remain in the simulator).
vsim -c top
library and design loading messages... then execute:
transcript on
force clk 1 50, 0 100 -repeat 100
run 500
run @5000
quit -f
Rename transcript files that you intend to use as DO files. They will be overwritten the next
time you run vsim if you don’t rename them. Also, simulator messages are already
commented out, but any messages generated from your design (and subsequently written
to the transcript file) will cause the simulator to pause. A transcript file that contains only
valid simulator commands will work fine; comment out anything else with a "#".
Stand-alone tools pick up project settings in command-line mode if they are invoked in the
project's root directory. If invoked outside the project directory, stand-alone tools pick up
project settings only if you set the MODELSIM environment variable to the path to the
project file (<Project_Root_Dir>/<Project_Name>.mpf).
Batch mode
Batch mode is an operational mode that provides neither an interactive command line nor
interactive windows. In a UNIX environment, vsim can be invoked in batch mode by
redirecting standard input using the “here-document” technique. In a Windows
environment, vsim is run from a Windows command prompt and standard input and output
are re-directed from and to files.
Here is an example of the "here-document" technique:
vsim top <<!
log -r *
run 100
do test.do
quit -f
!
Here is an example of a batch mode simulation using redirection of std input and output:
vsim counter < yourfile > outfile
Standards supported
ModelSim VHDL implements the VHDL language as defined by IEEE Standards
1076-1987, 1076-1993, and 1076-2002. ModelSim also supports the 1164-1993 Standard
Multivalue Logic System for VHDL Interoperability, and the 1076.2-1996 Standard VHDL
Mathematical Packages standards. Any design developed with ModelSim will be
compatible with any other VHDL system that is compliant with the 1076 specs.
ModelSim Verilog implements the Verilog language as defined by the IEEE Std 1364-1995
and 1364-2001. ModelSim Verilog also supports a partial implementation of
SystemVerilog 3.1, Accellera’s Extensions to Verilog® (see /<install_dir>/modeltech/
docs/technotes/svlog.note for implementation details). The Open Verilog International
Verilog LRM version 2.0 is also applicable to a large extent. Both PLI (Programming
Language Interface) and VCD (Value Change Dump) are supported for ModelSim PE and
SE users.
In addition, all products support SDF 1.0 through 3.0, VITAL 2.2b, VITAL’95 – IEEE
1076.4-1995, and VITAL 2000 – IEEE 1076.4-2000.
ModelSim implements the SystemC language based on the Open SystemC Initiative
(OSCI) SystemC 2.0.1 reference simulator.
ModelSim implements the simple subset of Accellera’s Property Specification Language
(PSL) version 1.1.
Assumptions
We assume that you are familiar with the use of your operating system and its graphical
interface.
We also assume that you have a working knowledge of VHDL, Verilog, and/or SystemC.
Although ModelSim is an excellent tool to use while learning HDL concepts and practices,
this document is not written to support that goal.
Finally, we assume that you have worked the appropriate lessons in the ModelSim Tutorial
and are familiar with the basic functionality of ModelSim. The ModelSim Tutorial is
available from the ModelSim Help menu. The ModelSim Tutorial is also available from the
Support page of our web site: www.model.com.
2 - Projects (UM-37)
This chapter discusses ModelSim "projects", a container for design files and their
associated simulation properties.
16 - C Debug (UM-399)
This chapter describes C Debug, a graphic interface to the gdb debugger that can be
used to debug FLI/PLI/VPI/SystemC C/C++ source code.
What is an "object"
Because ModelSim works with VHDL, Verilog, and System C, an “object” refers to any
valid design element in those languages. The word "object" is used whenever a specific
language reference is not needed. Depending on the context, “object” can refer to any of
the following:
Text conventions
Text conventions used in this manual include:
italic text provides emphasis and sets off filenames, pathnames, and
design unit names
The right angle (>) is used to connect menu choices when traversing menus as
in: File > Quit
UPPER CASE denotes file types used by ModelSim (e.g., DO, WLF, INI,
MPF, PDF, etc.)
ModelSim Tutorial PDF, HTML select Help > Documentation; also available from the Support
page of our web site: www.model.com
Command Help ASCII type help [command name] at the prompt in the Transcript pane
Error message help ASCII type verror <msgNum> at the Transcript or shell prompt
Tcl Man Pages (Tcl HTML select Help > Tcl Man Pages, or find contents.htm in
manual) \modeltech\docs\tcl_help_html
Updates
Access to the most current version of ModelSim:
www.model.com/downloads/default.asp
2 - Projects
Chapter contents
Introduction . . . . . . . . . . . . . . . . UM-38
What are projects?. . . . . . . . . . . . . . UM-38
What are the benefits of projects?. . . . . . . . . . UM-38
Project conversion between versions . . . . . . . . . UM-39
This chapter discusses ModelSim projects. Projects simplify the process of compiling and
simulating a design and are a great tool for getting started with ModelSim.
Introduction
What are projects?
Projects are collection entities for designs under specification or test. At a minimum,
projects have a root directory, a work library, and "metadata" which are stored in a .mpf file
located in a project's root directory. The metadata include compiler switch settings, compile
order, and file mappings. Projects may also include:
• Source files or references to source files
• other files such as READMEs or other project documentation
• local libraries
• references to global libraries
• Simulation Configurations (see "Creating a Simulation Configuration" (UM-48))
• Folders (see "Organizing projects with folders" (UM-50))
Important: Project metadata are updated and stored only for actions taken within the
project itself. For example, if you have a file in a project, and you compile that file from
the command line rather than using the project menu commands, the project will not
update to reflect any new compile settings.
See "Create Project dialog" (GR-37) for more details on this dialog.
After selecting OK, you will see a blank Project tab in the Workspace pane of the Main
window and the Add Items to the Project dialog.
workspace
The name of the current project is shown at the bottom left corner of the Main window.
Specify a name, file type, and folder location for the new file. See "Create Project File
dialog" (GR-43) for additional details on this dialog.
When you select OK, the file is listed in the Project tab.
See "Add file to Project dialog" (GR-44) for details on this dialog.
When you select OK, the file(s) is added to the Project tab.
Once compilation is finished, click the Library tab, expand library work by clicking the "+",
and you will see the compiled design units.
At this point you are ready to run the simulation and analyze your results. You often do this
by adding signals to the Wave window and running the simulation for a given period of
time. See the ModelSim Tutorial for examples.
Close a project
Select File > Close > Project or right-click in the Project tab and select Close Project. This
closes the Project tab but leaves the Library tab open in the workspace. Note that you
cannot close a project while a simulation is in progress.
Delete a project
Select File > Delete > Project. You cannot delete a project while it is open.
1 Select Compile > Compile Order or select it from the context menu in the Project tab.
2 Drag the files into the correct order or use the up and down arrow buttons. Note that you
can select multiple files and drag them simultaneously.
Grouping files
You can group two or more files in the Compile Order dialog so they are sent to the
compiler at the same time. For example, you might have one file with a bunch of Verilog
define statements and a second file that is a Verilog module. You would want to compile
these two files together.
To group files, follow these steps:
To ungroup files, select the group and click the Ungroup button.
1 Select File > Add to Project > Simulation Configuration or select it from the context
menu in the Project tab.
3 Specify the folder in which you want to place the configuration (see "Organizing projects
with folders" (UM-50)).
4 Select one or more design unit(s). Use the Control and/or Shift keys to select more than
one design unit. The design unit names appear in the Simulate field when you select
them.
5 Use the other tabs in the dialog to specify any required simulation options. See "Start
Simulation dialog" (GR-76) for details on the available options.
Click OK and the simulation configuration is added to the Project tab.
Optimization Configurations
Similar to Simulation Configurations, Optimization Configurations are named objects that
represent an optimized simulation. The process for creating and using them is similar to that
for Simulation Configurations (see above). You create them by selecting File > Add to
Project > Optimization Configuration and specifying various options in a dialog. See
"Optimization Configuration dialog" (GR-45) for more details on the dialog.
Adding a folder
To add a folder to your project, select File > Add to Project > Folder or right-click in the
Project tab and select Add to Project > Folder.
Specify the Folder Name, the location for the folder, and click OK. The folder will be
displayed in the Project tab.
You use the folders when you add new objects to the project. For example, when you add
a file, you can select which folder to place it in.
If you want to move a file into a folder later on, you can do so using the Properties dialog
for the file (right-click on the file and select Properties from the context menu).
On Windows platforms, you can also just drag-and-drop a file into a folder.
Important: Any changes you make to the compile properties outside of the project,
whether from the command line, the GUI, or the modelsim.ini file, will not affect the
properties of files already in the project.
To customize specific files, select the file(s) in the Project tab, right click on the file names,
and select Properties. The resulting Project Compiler Settings dialog varies depending on
the number and type of files you have selected. If you select a single VHDL or Verilog file,
you will see the General tab, Coverage tab, and the VHDL or Verilog tab, respectively. If
you select a SystemC file, you will see only the General tab. On the General tab, you will
see file properties such as Type, Location, and Size. If you select multiple files, the file
properties on the General tab are not listed. Finally, if you select both a VHDL file and a
Verilog file, you will see all tabs but no file information on the General tab.
Project settings
To modify project settings, right-click anywhere within the Project tab and select Project
Settings.
3 - Design libraries
Chapter contents
Design library overview . . . . . . . . . . . . . UM-58
Design unit information . . . . . . . . . . . . UM-58
Working library versus resource libraries . . . . . . . . UM-58
Archives . . . . . . . . . . . . . . . . UM-59
VHDL designs are associated with libraries, which are objects that contain compiled design
units. Verilog designs simulated within ModelSim are compiled into libraries as well.
Archives
By default, design libraries are stored in a directory structure with a sub-directory for each
design unit in the library. Alternatively, you can configure a design library to use archives.
In this case each design unit is stored in its own archive file. To create an archive, use the
-archive argument to the vlib command (CR-356).
Generally you would do this only in the rare case that you hit the reference count limit on
I-nodes due to the ".." entries in the lower-level directories (the maximum number of sub-
directories on UNIX and Linux is 65533). An example of an error message that is produced
when this limit is hit is:
mkdir: cannot create directory `65534': Too many links
Archives may also have limited value to customers seeking disk space savings.
Note that GMAKE won’t work with these archives on the IBM platform.
Creating a library
When you create a project (see "Getting started with projects" (UM-40)), ModelSim
automatically creates a working design library. If you don’t create a project, you need to
create a working design library before you run the compiler. This can be done from either
the command line or from the ModelSim graphic interface.
From the ModelSim prompt or a UNIX/DOS prompt, use this vlib command (CR-356):
vlib <directory_pathname>
To create a new library with the ModelSim graphic interface, select File > New > Library.
The options in this dialog are described under "Create a New Library dialog" (GR-38).
When you click OK, ModelSim creates the specified library directory and writes a
specially-formatted file named _info into that directory. The _info file must remain in the
directory to distinguish it as a ModelSim library.
The new map entry is written to the modelsim.ini file in the [Library] section. See
"[Library] library path variables" (UM-525) for more information.
Note: Remember that a design library is a special kind of directory; the only way to
create a library is to use the ModelSim GUI or the vlib command (CR-356). Do not try to
create libraries using UNIX, DOS, or Windows commands.
The Library tab has a context menu with various commands that you access by clicking
your right mouse button (Windows—2nd button, UNIX—3rd button) in the Library tab.
You may invoke this command from either a UNIX/DOS prompt or from the command line
within ModelSim.
The vmap (CR-370) command adds the mapping to the library section of the modelsim.ini
file. You can also modify modelsim.ini manually by adding a mapping line. To do this, use
a text editor and add a line under the [Library] section heading using the syntax:
<logical_name> = <directory_pathname>
More than one logical name can be mapped to a single directory. For example, suppose the
modelsim.ini file in the current working directory contains following lines:
[Library]
work = /usr/rick/design
my_asic = /usr/rick/design
This would allow you to use either the logical name work or my_asic in a library or use
clause to refer to the same design library.
The vmap command (CR-370) can also be used to display the mapping of a logical library
name to a directory. To do this, enter the shortened form of the command:
vmap <logical_name>
Moving a library
Individual design units in a design library cannot be moved. An entire design library can
be moved, however, by using standard operating system commands for moving a directory
or an archive.
Important: Resource libraries are specified differently for Verilog and VHDL. For
Verilog you use either the -L or -Lf argument to vlog (CR-358). See "Library usage" (UM-
117) for more information.
Predefined libraries
Certain resource libraries are predefined in standard VHDL. The library named std
contains the packages standard and textio, which should not be modified. The contents of
these packages and other aspects of the predefined language environment are documented
in the IEEE Standard VHDL Language Reference Manual, Std 1076. See also, "Using the
TextIO package" (UM-88).
A VHDL use clause can be specified to select particular declarations in a library or package
that are to be visible within a design unit during compilation. A use clause references the
compiled version of the package—not the source.
By default, every VHDL design unit is assumed to contain the following declarations:
LIBRARY std, work;
USE std.standard.all
To specify that all declarations in a library or package can be referenced, add the suffix .all
to the library/package name. For example, the use clause above specifies that all
declarations in the package standard, in the design library named std, are to be visible to
the VHDL design unit immediately following the use clause. Other libraries or packages
are not visible unless they are explicitly specified using a library or use clause.
Another predefined library is work, the library where a design unit is stored after it is
compiled as described earlier. There is no limit to the number of libraries that can be
referenced, but only one library is modified during compilation.
Make sure your current directory is the modeltech install directory before you run this file.
Note: Because accelerated subprograms require attributes that are available only under
the 1993 standard, many of the libraries are built using vcom (CR-311) with the -93
option.
Shell scripts are provided for UNIX (rebuild_libs.csh and rebuild_libs.sh). To rebuild the
libraries, execute one of the rebuild_libs scripts while in the modeltech directory.
An important feature of -refresh is that it rebuilds the library image without using source
code. This means that models delivered as compiled libraries without source code can be
rebuilt for a specific release of ModelSim (4.6 and later only). In general, this works for
moving forwards or backwards on a release. Moving backwards on a release may not work
if the models used compiler switches or directives that do not exist in the older release.
Note: You don't need to regenerate the std, ieee, vital22b, and verilog libraries. Also, you
cannot use the -refresh option to update libraries that were built before the 4.6 release.
1 Set the environment variable MGC_LOCATION_MAP to the path to your location map
file.
$IEEE
/usr/modeltech/ieee
Pathname syntax
The logical pathnames must begin with $ and the physical pathnames must begin with /.
The logical pathname is followed by one or more equivalent physical pathnames. Physical
pathnames are equivalent if they refer to the same physical directory (they just have
different pathnames on different systems).
Important: The FPGA libraries you import must be pre-compiled. Most FPGA vendors
supply pre-compiled libraries configured for use with ModelSim.
Note: -nodebug encrypts entire files. The Verilog `protect compiler directive allows
you to encrypt regions within a file. See "ModelSim compiler directives" (UM-155) for
details.
When you compile with -nodebug, all source text, identifiers, and line number information
are stripped from the resulting compiled object, so ModelSim cannot locate or display any
information of the model except for the external pins. Specifically, this means that:
• a Source window will not display the design units’ source code
• a structure pane will not display the internal structure
• the Objects pane will not display internal signals
• the Active Processes pane will not display internal processes
• the Locals pane will not display internal variables
• none of the hidden objects may be accessed through the Dataflow window or with
ModelSim commands
You can access the design units comprising your model via the library, and you may invoke
vsim (CR-373) directly on any of these design units and see the ports. To restrict even this
access in the lower levels of your design, you can use the following -nodebug options when
you compile:
vlog -nodebug=pli prevents the use of PLI functions to interrogate the module for
information
Don’t use the =ports option on a design without hierarchy, or on the top level of a
hierarchical design. If you do, no ports will be visible for simulation. Rather, compile all
lower portions of the design with -nodebug=ports first, then compile the top level with
-nodebug alone.
Design units or modules compiled with -nodebug can only instantiate design units or
modules that are also compiled -nodebug.
4 - VHDL simulation
Chapter contents
Compiling VHDL files. . . . . . . . . . . . . . UM-73
Creating a design library . . . . . . . . . . . . UM-73
Invoking the VHDL compiler . . . . . . . . . . . UM-73
Dependency checking . . . . . . . . . . . . . UM-73
Range and index checking . . . . . . . . . . . UM-74
Subprogram inlining . . . . . . . . . . . . . UM-74
Differences between language versions . . . . . . . . UM-75
This chapter provides an overview of compilation and simulation for VHDL; using the
TextIO package with ModelSim; ModelSim’s implementation of the VITAL (VHDL
Initiative Towards ASIC Libraries) specification for ASIC modeling; and documentation
on ModelSim’s special built-in utilities package.
The TextIO package is defined within the VHDL Language Reference Manual, IEEE Std
1076; it allows human-readable text input from a declared source within a VHDL file
during simulation.
This creates a library named work. By default, compilation results are stored in the work
library.
The work library is actually a subdirectory named work. This subdirectory contains a
special file named _info. Do not create libraries using UNIX, MS Windows, or DOS
commands – always use the vlib command (CR-356).
See "Design libraries" (UM-57) for additional information on working with libraries.
Dependency checking
Dependent design units must be reanalyzed when the design units they depend on are
changed in the library. vcom (CR-311) determines whether or not the compilation results
have changed. For example, if you keep an entity and its architectures in the same source
file and you modify only an architecture and recompile the source file, the entity
compilation results will remain unchanged and you will not have to recompile design units
that depend on the entity.
Subprogram inlining
ModelSim attempts to inline subprograms at compile time to improve simulation
performance. This happens automatically and should be largely transparent. However, you
can disable automatic inlining two ways:
• Invoke vcom (CR-311) with the -O0 or -O1 argument
• Use the mti_inhibit_inline attribute as described below
Single-stepping through a simulation varies slightly depending on whether inlining
occurred. When single-stepping to a subprogram call that has not been inlined, the
simulator stops first at the line of the call, and then proceeds to the line of the first
executable statement in the called subprogram. If the called subprogram has been inlined,
the simulator does not first stop at the subprogram call, but stops immediately at the line of
the first executable statement.
mti_inhibit_inline attribute
You can disable inlining for individual design units (a package, architecture, or entity) or
subprograms with the mti_inhibit_inline attribute. Follow these rules to use the attribute:
• Declare the attribute within the design unit's scope as follows:
attribute mti_inhibit_inline : boolean;
• Assign the value true to the attribute for the appropriate scope. For example, to inhibit
inlining for a particular function (e.g., "foo"), add the following attribute assignment:
attribute mti_inhibit_inline of foo : procedure is true;
To inhibit inlining for a particular package (e.g., "pack"), add the following attribute
assignment:
attribute mti_inhibit_inline of pack : package is true;
• Purity of NOW
In VHDL-93 the function "now" is impure. Consequently, any function that invokes
"now" must also be declared to be impure. Such calls to "now" occur in VITAL. A typical
error message:
"Cannot call impure function 'now' from inside pure function '<name>'"
• Files
File syntax and usage changed between VHDL-87 and VHDL-93. In many cases vcom
issues a warning and continues:
"Using 1076-1987 syntax for file declaration."
In addition, when files are passed as parameters, the following warning message is
produced:
"Subprogram parameter name is declared using VHDL 1987 syntax."
This message often involves calls to endfile(<name>) where <name> is a file parameter.
If you compile the package header with VHDL-87 and the body with VHDL-93 or
VHDL-2002, you will get an error message such as:
"** Error: mixed_package_b.vhd(4): Parameter kinds do not conform between
declarations in package header and body: 'out_file'."
• Direction of concatenation
To solve some technical problems, the rules for direction and bounds of concatenation
were changed from VHDL-87 to VHDL-93. You won't see any difference in simple
variable/signal assignments such as:
v1 := a & b;
But if you (1) have a function that takes an unconstrained array as a parameter, (2) pass
a concatenation expression as a formal argument to this parameter, and (3) the body of
the function makes assumptions about the direction or bounds of the parameter, then you
will get unexpected results. This may be a problem in environments that assume all arrays
have "downto" direction.
• xnor
"xnor" is a reserved word in VHDL-93. If you declare an xnor function in VHDL-87
(without quotes) and compile it under VHDL-2002, you will get an error message like
the following:
** Error: xnor.vhd(3): near "xnor": expecting: STRING IDENTIFIER
• 'FOREIGN attribute
In VHDL-93 package STANDARD declares an attribute 'FOREIGN. If you declare your
own attribute with that name in another package, then ModelSim issues a warning such
as the following:
-- Compiling package foopack
by
"range nul downto 'ÿ' is null" -- range is nul downto y(umlaut)
vsim (CR-373) is capable of annotating a design using VITAL compliant models with timing
data from an SDF file. You can specify the min:typ:max delay by invoking vsim with the
-sdfmin, -sdftyp, or -sdfmax option. Using the SDF file f1.sdf in the current work
directory, the following invocation of vsim annotates maximum timing values for the
design unit my_asic:
vsim -sdfmax /my_asic=f1.sdf my_asic
By default, the timing checks within VITAL models are enabled. They can be disabled with
the +notimingchecks option. For example:
vsim +notimingchecks topmod
Clearly you need to be careful when doing this type of operation. If the resolution set by -t
is larger than a delay value in your design, the delay values in that design unit are rounded
to the closest multiple of the resolution. In the example above, a delay of 4 ps would be
rounded to 0 ps.
Default binding
By default ModelSim performs default binding when you load the design with vsim (CR-
373). The advantage of performing default binding at load time is that it provides more
flexibility for compile order. Namely, entities don't necessarily have to be compiled before
other entities/architectures which instantiate them.
However, you can force ModelSim to perform default binding at compile time. This may
allow you to catch design errors (e.g., entities with incorrect port lists) earlier in the flow.
Use one of these two methods to change when default binding occurs:
• Specify the -bindAtCompile argument to vcom (CR-311)
• Set the BindAtCompile (UM-527) variable in the modelsim.ini to 1 (true)
Delta delays
Event-based simulators such as ModelSim may process many events at a given simulation
time. Multiple signals may need updating, statements that are sensitive to these signals
must be executed, and any new events that result from these statements must then be
queued and executed as well. The steps taken to evaluate the design without advancing
simulation time are referred to as "delta times" or just "deltas."
The diagram below represents the process for VHDL designs. This process continues until
the end of simulation time.
Execute
concurrent Advance
statements at delta time
current time
Any events to No
process?
Yes
Execute concurrent
statements that are
sensitive to events
This mechanism in event-based simulators may cause unexpected results. Consider the
following code snippet:
clk2 <= clk;
In this example you have two synchronous processes, one triggered with clk and the other
with clk2. To your surprise, the signals change in the clk2 process on the same edge as they
are set in the clk process. As a result, the value of inp appears at s1 rather than s0.
During simulation an event on clk occurs (from the testbench). From this event ModelSim
performs the "clk2 <= clk" assignment and the process which is sensitive to clk. Before
advancing the simulation time, ModelSim finds that the process sensitive to clk2 can also
be run. Since there are no delays present, the effect is that the value of inp appears at s1 in
the same simulation cycle.
In order to get the expected results, you must do one of the following:
• Insert a delay at every output
• Make certain to use the same clock
• Insert a delta delay
To insert a delta delay, you would modify the code like this:
process (rst, clk)
begin
if(rst = '0')then
s0 <= '0';
elsif(clk'event and clk='1') then
s0 <= inp;
s0_delayed <= s0;
end if;
end process;
The best way to debug delta delay problems is observe your signals in the List window.
There you can see how values change at each delta time.
1 If timing for your design is fixed, include all timing data when you create the elaboration
file (using the -sdf<type> instance=<filename> argument). If your timing is not fixed
in a Verilog design, you’ll have to use $sdf_annotate system tasks. Note that use of
$sdf_annotate causes timing to be applied after elaboration.
2 Apply all normal vsim arguments when you create the elaboration file. Some arguments
(primarily related to stimulus) may be superseded later during loading of the elaboration
file (see "Modifying stimulus" (UM-84) below).
3 Load the elaboration file along with any arguments that modify the stimulus (see below).
Important: Elaboration files can be created in command-line mode only. You cannot
create an elaboration file while running the ModelSim GUI.
Modification of an argument that was specified at elaboration file creation, in most cases,
causes the previous value to be replaced with the new value. Usage of the -quiet argument
at elaboration load causes the mode to be toggled from its elaboration creation setting.
All other vsim arguments must be specified when you create the elaboration file, and they
cannot be used when you load the elaboration file.
Important: The elaboration file must be loaded under the same environment in which it
was created. The same environment means the same hardware platform, the same OS
and patch version, and the same version of any PLI/FLI code loaded in the simulation.
Modifying stimulus
A primary use of elaboration files is repeatedly simulating the same design with different
stimulus. The following mechanisms allow you to modify stimulus for each run.
• Use of the change command to modify parameters or generic values. This affects values
only; it has no effect on triggers, compiler directives, or generate statements that
reference either a generic or parameter.
• Use of the -filemap_elab <HDLfilename>=<NEWfilename> argument to establish a
map between files named in the elaboration file. The <HDLfilename> file name, if it
appears in the design as a file name (for example, a VHDL FILE object as well as some
Verilog sysfuncs that take file names), is substituted with the <NEWfilename> file
name. This mapping occurs before environment variable expansion and can’t be used to
redirect stdin/stdout.
• VCD stimulus files can be specified when you load the elaboration file. Both vcdread and
vcdstim are supported. Specifying a different VCD file when you load the elaboration file
supersedes a stimulus file you specify when you create the elaboration file.
• In Verilog, the use of +args which are readable by the PLI routine mc_scan_plusargs().
+args values specified when you create the elaboration file are superseded by +args
values specified when you load the elaboration file.
Syntax
See the vsim command (CR-373) for details on -elab, -elab_cont, -elab_defer_fli,
-compress_elab, -filemap_elab, and -load_elab.
Example
Upon first simulating the design, use vsim -elab <filename>
<library_name.design_unit> to create an elaboration file that will be used in subsequent
simulations.
In subsequent simulations you simply load the elaboration file (rather than the design) with
vsim -load_elab <filename>.
To change the stimulus without recoding, recompiling, and reloading the entire design,
Modelsim allows you to map the stimulus file (or files) of the original design unit to an
alternate file (or files) with the -filemap_elab switch. For example, the VHDL code for
initiating stimulus might be:
FILE vector_file : text IS IN "vectors";
Checkpoint exclusions
You can also control checkpoint compression using the modelsim.ini file in the [vsim]
section (use the same 0 or 1 switch):
[vsim]
CheckpointCompressMode = <switch>
You can specify a full or relative path as the file_logical_name; for example (VHDL’87):
file filename : TEXT is in "/usr/rick/myfile";
Normally if a file is declared within an architecture, process, or package, the file is opened
when you start the simulator and is closed when you exit from it. If a file is declared in a
subprogram, the file is opened when the subprogram is called and closed when execution
RETURNs from the subprogram. Alternatively, the opening of files can be delayed until
the first read or write by setting the DelayFileOpen variable in the modelsim.ini file. Also,
the number of concurrently open files can be controlled by the ConcurrentFileLimit
variable. These variables help you manage a large number of files during simulation. See
Appendix B - ModelSim variables for more details.
In the TextIO package, the WRITE procedure is overloaded for the types STRING and
BIT_VECTOR. These lines are reproduced here:
procedure WRITE(L: inout LINE; VALUE: in BIT_VECTOR;
JUSTIFIED: in SIDE:= RIGHT; FIELD: in WIDTH := 0);
The error occurs because the argument "hello" could be interpreted as a string or a bit
vector, but the compiler is not allowed to determine the argument type until it knows which
function is being called.
The following procedure call also generates an error:
WRITE (L, "010101");
This call is even more ambiguous, because the compiler could not determine, even if
allowed to, whether the argument "010101" should be interpreted as a string or a bit vector.
There are two possible solutions to this problem:
• Use a qualified expression to specify the type, as in:
WRITE (L, string’("hello"));
The WRITE_STRING procedure simply defines the value to be a STRING and calls the
WRITE procedure, but it serves as a shell around the WRITE procedure that solves the
overloading problem. For further details, refer to the WRITE_STRING procedure in the
io_utils package, which is located in the file <install_dir>/modeltech/examples/
io_utils.vhd.
Dangling pointers
Dangling pointers are easily created when using the TextIO package, because
WRITELINE de-allocates the access type (pointer) that is passed to it. Following are
examples of good and bad VHDL coding styles:
Bad VHDL (because L1 and L2 both point to the same buffer):
READLINE (infile, L1); -- Read and allocate buffer
L2 := L1; -- Copy pointers
WRITELINE (outfile, L1); -- Deallocate buffer
As you can see, this function is commented out of the standard TextIO package. This is
because the ENDFILE function is implicitly declared, so it can be used with files of any
type, not just files of type TEXT.
Then include the identifier for this file ("myinput" in this example) in the READLINE or
WRITELINE procedure call.
Providing stimulus
You can stimulate and test a design by reading vectors from a file, using them to drive
values onto signals, and testing the results. A VHDL test bench has been included with the
ModelSim install files as an example. Check for this file:
<install_dir>/modeltech/examples/stimulus.vhd
VITAL packages
VITAL 1995 accelerated packages are pre-compiled into the ieee library in the installation
directory. VITAL 2000 accelerated packages are pre-compiled into the vital2000 library.
If you need to use the newer library, you either need to change the ieee library mapping or
add a use clause to your VHDL code to access the VITAL 2000 packages.
To change the ieee library mapping, issue the following command:
vmap ieee <modeltech>/vital2000
Note that if your design uses two libraries -one that depends on vital95 and one that depends
on vital2000 - then you will have to change the references in the source code to vital2000.
Changing the library mapping will not work.
Util package
The util package, included in ModelSim versions 5.5 and later, serves as a container for
various VHDL utilities. The package is part of the modelsim_lib library which is located in
the modeltech tree and is mapped in the default modelsim.ini file.
To access the utilities in the package, you would add lines like the following to your VHDL
code:
library modelsim_lib;
use modelsim_lib.util.all;
get_resolution
get_resolution returns the current simulator resolution as a real number. For example, 1
femtosecond corresponds to 1e-15.
Syntax
resval := get_resolution;
Returns
Arguments
None
Related functions
to_real() (UM-98)
to_time() (UM-99)
Example
If the simulator resolution is set to 10ps, and you invoke the command:
resval := get_resolution;
init_signal_driver()
The init_signal_driver() procedure drives the value of a VHDL signal or Verilog net onto
an existing VHDL signal or Verilog net. This allows you to drive signals or nets at any level
of the design hierarchy from within a VHDL architecture (e.g., a testbench).
See init_signal_driver (UM-419) in Chapter 17 - Signal Spy for complete details.
init_signal_spy()
The init_signal_spy() utility mirrors the value of a VHDL signal or Verilog register/net
onto an existing VHDL signal or Verilog register. This allows you to reference signals,
registers, or nets at any level of hierarchy from within a VHDL architecture (e.g., a
testbench).
See init_signal_spy (UM-422) in Chapter 17 - Signal Spy for complete details.
signal_force()
The signal_force() procedure forces the value specified onto an existing VHDL signal or
Verilog register or net. This allows you to force signals, registers, or nets at any level of the
design hierarchy from within a VHDL architecture (e.g., a testbench). A signal_force works
the same as the force command (CR-180) with the exception that you cannot issue a
repeating force.
See In this example, the value of /top/uut/inst1/sig1 is mirrored onto /top/top_sig1.
signal_force (UM-425) in Chapter 17 - Signal Spy for complete details.
signal_release()
The signal_release() procedure releases any force that was applied to an existing VHDL
signal or Verilog register or net. This allows you to release signals, registers, or nets at any
level of the design hierarchy from within a VHDL architecture (e.g., a testbench). A
signal_release works the same as the noforce command (CR-208).
See signal_release (UM-427) in Chapter 17 - Signal Spy for complete details.
to_real()
to_real() converts the physical type time value into a real value with respect to the current
simulator resolution. The precision of the converted value is determined by the simulator
resolution. For example, if you were converting 1900 fs to a real and the simulator
resolution was ps, then the real value would be 2.0 (i.e., 2 ps).
Syntax
realval := to_real(timeval);
Returns
Arguments
Related functions
get_resolution (UM-96)
to_time() (UM-99)
Example
If the simulator resolution is set to ps, and you enter the following function:
realval := to_real(12.99 ns);
then the value returned to realval would be 12990.0. If you wanted the returned value to be
in units of nanoseconds (ns) instead, you would use the get_resolution (UM-96) function to
recalculate the value:
realval := 1e+9 * (to_real(12.99 ns)) * get_resolution();
If you wanted the returned value to be in units of femtoseconds (fs), you would enter the
function this way:
realval := 1e+15 * (to_real(12.99 ns)) * get_resolution();
to_time()
to_time() converts a real value into a time value with respect to the current simulator
resolution. The precision of the converted value is determined by the simulator resolution.
For example, if you were converting 5.9 to a time and the simulator resolution was ps, then
the time value would be 6 ps.
Syntax
timeval := to_time(realval);
Returns
Arguments
Related functions
get_resolution (UM-96)
to_real() (UM-98)
Example
If the simulator resolution is set to ps, and you enter the following function:
timeval := to_time(72.49);
Modeling memory
As a VHDL user, you might be tempted to model a memory using signals. Two common
simulator problems are the likely result:
• You may get a "memory allocation error" message, which typically means the simulator
ran out of memory and failed to allocate enough storage.
• Or, you may get very long load, elaboration, or run times.
These problems are usually explained by the fact that signals consume a substantial amount
of memory (many dozens of bytes per bit), all of which needs to be loaded or initialized
before your simulation starts.
Modeling memory with variables or protected types instead provides some excellent
performance benefits:
• storage required to model the memory can be reduced by 1-2 orders of magnitude
• startup and run times are reduced
• associated memory allocation errors are eliminated
In the VHDL example below, we illustrate three alternative architectures for entity
memory:
• Architecture bad_style_87 uses a vhdl signal to store the ram data.
• Architecture style_87 uses variables in the memory process
• Architecture style_93 uses variables in the architecture.
For large memories, architecture bad_style_87 runs many times longer than the other two,
and uses much more memory. This style should be avoided.
Architectures style_87 and style_93 work with equal efficiently. However, VHDL 1993
offers additional flexibility because the ram storage can be shared between multiple
processes. For example, a second process is shown that initializes the memory; you could
add other processes to create a multi-ported memory.
To implement this model, you will need functions that convert vectors to integers. To use
it you will probably need to convert integers to vectors.
Example functions are provided below in package "conversions".
For completeness sake we also show an example using VHDL 2002 protected types, though
it offers no advantages over VHDL 1993 shared variables.
entity memory is
generic(add_bits : integer := 12;
data_bits : integer := 32);
port(add_in : in std_ulogic_vector(add_bits-1 downto 0);
data_in : in std_ulogic_vector(data_bits-1 downto 0);
data_out : out std_ulogic_vector(data_bits-1 downto 0);
cs, mwrite : in std_ulogic;
do_init : in std_ulogic);
subtype word is std_ulogic_vector(data_bits-1 downto 0);
------------------------------------------------------------
------------------------------------------------------------
library ieee;
use ieee.std_logic_1164.all;
package conversions is
function sulv_to_natural(x : std_ulogic_vector) return
natural;
function natural_to_sulv(n, bits : natural) return
std_ulogic_vector;
end conversions;
if failure then
return 0;
else
return n;
end if;
end sulv_to_natural;
end loop;
return x;
end natural_to_sulv;
end conversions;
’02 example
---------------------------------------------------------------------------
---
-- Source: sp_syn_ram_protected.vhd
-- Component: VHDL synchronous, single-port RAM
-- Remarks: Various VHDL examples: random access memory (RAM)
---------------------------------------------------------------------------
---
LIBRARY ieee;
USE ieee.std_logic_1164.ALL;
USE ieee.numeric_std.ALL;
ENTITY sp_syn_ram_protected IS
GENERIC (
data_width : positive := 8;
addr_width : positive := 3
);
PORT (
inclk : IN std_logic;
outclk : IN std_logic;
we : IN std_logic;
addr : IN unsigned(addr_width-1 DOWNTO 0);
data_in : IN std_logic_vector(data_width-1 DOWNTO 0);
data_out : OUT std_logic_vector(data_width-1 DOWNTO 0)
);
END sp_syn_ram_protected;
return mem(to_integer(addr));
END;
BEGIN
BEGIN
IF (inclk'event AND inclk = '1') THEN
IF (we = '1') THEN
memory.write(data_in, addr);
END IF;
END IF;
END intarch;
---------------------------------------------------------------------------
---
-- Source: ram_tb.vhd
-- Component: VHDL testbench for RAM memory example
-- Remarks: Simple VHDL example: random access memory (RAM)
---------------------------------------------------------------------------
---
LIBRARY ieee;
USE ieee.std_logic_1164.ALL;
USE ieee.numeric_std.ALL;
ENTITY ram_tb IS
END ram_tb;
-------------------------------------------
-- Component declaration single-port RAM
-------------------------------------------
COMPONENT sp_syn_ram_protected
GENERIC (
data_width : positive := 8;
addr_width : positive := 3
);
PORT (
inclk : IN std_logic;
outclk : IN std_logic;
we : IN std_logic;
addr : IN unsigned(addr_width-1 DOWNTO 0);
data_in : IN std_logic_vector(data_width-1 DOWNTO 0);
data_out : OUT std_logic_vector(data_width-1 DOWNTO 0)
);
END COMPONENT;
-------------------------------------------
-- Intermediate signals and constants
-------------------------------------------
SIGNAL addr : unsigned(19 DOWNTO 0);
SIGNAL inaddr : unsigned(3 DOWNTO 0);
SIGNAL outaddr : unsigned(3 DOWNTO 0);
SIGNAL data_in : unsigned(31 DOWNTO 0);
SIGNAL data_in1 : std_logic_vector(7 DOWNTO 0);
SIGNAL data_sp1 : std_logic_vector(7 DOWNTO 0);
SIGNAL we : std_logic;
SIGNAL clk : std_logic;
CONSTANT clk_pd : time := 100 ns;
BEGIN
---------------------------------------------------
-- instantiations of single-port RAM architectures.
-- All architectures behave equivalently, but they
-- have different implementations. The signal-based
-- architecture (rtl) is not a recommended style.
---------------------------------------------------
spram1 : entity work.sp_syn_ram_protected
GENERIC MAP (
data_width => 8,
addr_width => 12)
PORT MAP (
inclk => clk,
outclk => clk,
we => we,
addr => addr(11 downto 0),
data_in => data_in1,
data_out => data_sp1);
-------------------------------------------
-- clock generator
-------------------------------------------
clock_driver : PROCESS
BEGIN
clk <= '0';
WAIT FOR clk_pd / 2;
LOOP
clk <= '1', '0' AFTER clk_pd / 2;
WAIT FOR clk_pd;
END LOOP;
END PROCESS;
-------------------------------------------
-- data-in process
-------------------------------------------
datain_drivers : PROCESS(data_in)
BEGIN
data_in1 <= std_logic_vector(data_in(7 downto 0));
END PROCESS;
-------------------------------------------
-- simulation control process
-------------------------------------------
ctrl_sim : PROCESS
BEGIN
FOR i IN 0 TO 1023 LOOP
we <= '1';
data_in <= to_unsigned(9000 + i, data_in'length);
addr <= to_unsigned(i, addr'length);
inaddr <= to_unsigned(i, inaddr'length);
outaddr <= to_unsigned(i, outaddr'length);
WAIT UNTIL clk'EVENT AND clk = '0';
WAIT UNTIL clk'EVENT AND clk = '0';
we <= '0';
addr <= to_unsigned(i, addr'length);
outaddr <= to_unsigned(i, outaddr'length);
WAIT UNTIL clk'EVENT AND clk = '0';
WAIT UNTIL clk'EVENT AND clk = '0';
END LOOP;
ASSERT false
REPORT "### End of Simulation!"
SEVERITY failure;
END PROCESS;
END testbench;
At time 0, process p makes an event for time 10ms. When synch goes to 1 at 10 ns, the event
at 10 ms is marked as cancelled but not deleted, and a new event is scheduled at 10ms +
10ns. The cancelled events are not reclaimed until time 10ms is reached and the cancelled
event is processed. As a result there will be 500000 (10ms/20ns) cancelled but un-deleted
events. Once 10ms is reached, memory will no longer increase because the simulator will
be reclaiming events as fast as they are added.
For projected waveforms the following would behave the same way:
signals synch : bit := '0';
...
p: process(synch)
begin
output <= '0', '1' after 10ms;
end process;
entity test is
end test;
5 - Verilog simulation
Chapter contents
Introduction . . . . . . . . . . . . . . . UM-113
ModelSim Verilog basic flow . . . . . . . . . . UM-113
Compiling Verilog files . . . . . . . . . . . . UM-114
Incremental compilation . . . . . . . . . . . UM-115
Library usage . . . . . . . . . . . . . . UM-117
Verilog-XL compatible compiler arguments . . . . . . UM-119
Verilog-XL `uselib compiler directive . . . . . . . UM-120
Verilog configurations . . . . . . . . . . . UM-122
Verilog generate statements . . . . . . . . . . UM-123
Optimizing Verilog designs . . . . . . . . . . . UM-124
Running vopt on your design . . . . . . . . . . UM-124
Naming the optimized design . . . . . . . . . . UM-125
Enabling design object visibility with the +acc option . . . UM-126
Optimizing gate-level designs. . . . . . . . . . UM-127
Event order and optimized designs . . . . . . . . UM-128
Timing checks in optimized designs . . . . . . . . UM-128
Introduction
This chapter describes how to compile, optimize, and simulate Verilog designs with
ModelSim. ModelSim implements the Verilog language as defined by the IEEE Standards
1364-1995 and 1364-2001 and Accelera’s SystemVerilog 3.1. We recommend that you
obtain these specifications for reference.
The following functionality is partially implemented in ModelSim Verilog:
• Verilog Procedural Interface (VPI) (see /<install_dir>/modeltech/docs/technotes/
Verilog_VPI.note for details)
• SystemVerilog 3.1, Accellera’s Extensions to Verilog® (see /<install_dir>/modeltech/
docs/technotes/sysvlog.note for implementation details)
1 Compile your Verilog code into one or more libraries using the vlog command (CR-358).
See "Compiling Verilog files" (UM-114) for details.
2 Elaborate and optimize your design using the vopt command (CR-371). See "Optimizing
Verilog designs" (UM-124) for details.
3 Load your design with the vsim command (CR-373). See "Simulating Verilog designs"
(UM-129) for details.
This creates a library named work. By default compilation results are stored in the work
library.
The work library is actually a subdirectory named work. This subdirectory contains a
special file named _info. Do not create libraries using UNIX commands – always use the
vlib command (CR-356).
See "Design libraries" (UM-57) for additional information on working with libraries.
After compiling top.v, vlog will scan the vlog_lib library for files with modules with the
same name as primitives referenced, but undefined in top.v. The use of +libext+.v+.u
implies filenames with a .v or .u suffix (any combination of suffixes may be used). Only
referenced definitions will be compiled.
Incremental compilation
By default, ModelSim Verilog supports incremental compilation of designs, thus saving
compilation time when you modify your design. Unlike other Verilog simulators, there is
no requirement that you compile the entire design in one invocation of the compiler.
You are not required to compile your design in any particular order because all module and
UDP instantiations and external hierarchical references are resolved when the design is
loaded by the simulator.
Incremental compilation is made possible by deferring these bindings, and as a result some
errors cannot be detected during compilation. Commonly, these errors include: modules
that were referenced but not compiled, incorrect port connections, and incorrect
hierarchical references.
Example
The following example shows how a hierarchical design can be compiled in top-down
order:
Contents of top.v:
module top;
or2 or2_i (n1, a, b);
and2 and2_i (n2, n1, c);
endmodule
Contents of and2.v:
module and2(y, a, b);
output y;
input a, b;
and(y, a, b);
endmodule
Contents of or2.v:
module or2(y, a, b);
output y;
input a, b;
or(y, a, b);
endmodule
Note that the compiler lists each module as a top level module, although, ultimately, only
top is a top-level module. If a module is not referenced by another module compiled in the
same invocation of the compiler, then it is listed as a top level module. This is just an
informative message and can be ignored during incremental compilation. The message is
more useful when you compile an entire design in one invocation of the compiler and need
to know the top-level module names for the simulator. For example,
% vlog top.v and2.v or2.v
-- Compiling module top
-- Compiling module and2
-- Compiling module or2
Now, suppose that you modify the functionality of the or2 module:
% vlog -incr top.v and2.v or2.v
-- Skipping module top
-- Skipping module and2
-- Compiling module or2
The compiler informs you that it skipped the modules top and and2, and compiled or2.
Automatic incremental compilation is intelligent about when to compile a module. For
example, changing a comment in your source code does not result in a recompile; however,
changing the compiler command line arguments results in a recompile of all modules.
Note: Changes to your source code that do not change functionality but that do affect
source code line numbers (such as adding a comment line) will cause all affected
modules to be recompiled. This happens because debug information must be kept current
so that ModelSim can trace back to the correct areas of the source code.
Library usage
All modules and UDPs in a Verilog design must be compiled into one or more libraries.
One library is usually sufficient for a simple design, but you may want to organize your
modules into various libraries for a complex design. If your design uses different modules
having the same name, then you are required to put those modules in different libraries
because design unit names must be unique within a library.
The following is an example of how you may organize your ASIC cells into one library and
the rest of your design into another:
% vlib work
% vlib asiclib
% vlog -work asiclib and2.v or2.v
-- Compiling module and2
-- Compiling module or2
Note that the first compilation uses the -work asiclib argument to instruct the compiler to
place the results in the asiclib library rather than the default work library.
top
modA modB
lib1: lib2:
modA modB
cellX cellX
The normal library search rules will fail in this situation. For example, if you load the
design as follows:
vsim -L lib1 -L lib2 top
both instantiations of cellX resolve to the lib1 version of cellX. On the other hand, if you
specify -L lib2 -L lib1, both instantiations of cellX resolve to the lib2 version of cellX.
To handle this situation, ModelSim implements a special interpretation of the expression
-L work. When you specify -L work first in the search library arguments you are directing
vsim to search for the instantiated module or UDP in the library that contains the module
that does the instantiation.
In the example above you would invoke vsim as follows:
vsim -L work -L lib1 -L lib2 top
Since the `uselib directives are embedded in the Verilog source code, there is more
flexibility in defining the source libraries for the instantiations in the design. The
appearance of a `uselib directive in the source code explicitly defines how instantiations
that follow it are resolved, completely overriding any previous `uselib directives.
-compile_uselibs argument
Use the -compile_uselibs argument to vlog (CR-358) to reference `uselib directives. The
argument finds the source files referenced in the directive, compiles them into
automatically created object libraries, and updates the modelsim.ini file with the logical
mappings to the libraries.
When using -compile_uselibs, ModelSim determines into which directory to compile the
object libraries by choosing, in order, from the following three values:
• The directory name specified by the -compile_uselibs argument. For example,
-compile_uselibs=./mydir
The following code fragment and compiler invocation show how two different modules
that have the same name can be instantiated within the same design:
module top;
`uselib dir=/h/vendorA libext=.v
NAND2 u1(n1, n2, n3);
`uselib dir=/h/vendorB libext=.v
NAND2 u2(n4, n5, n6);
endmodule
This allows the NAND2 module to have different definitions in the vendorA and vendorB
libraries.
`uselib is persistent
As mentioned above, the appearance of a `uselib directive in the source code explicitly
defines how instantiations that follow it are resolved. This may result in unexpected
consequences. For example, consider the following compile command:
vlog -compile_uselibs dut.v srtr.v
Assume that dut.v contains a `uselib directive. Since srtr.v is compiled after dut.v, the
`uselib directive is still in effect. When srtr is loaded it is using the `uselib directive from
dut.v to decide where to locate modules. If this is not what you intend, then you need to put
an empty `uselib at the end of dut.v to "close" the previous `uselib statement.
Verilog configurations
The Verilog 2001 specification added configurations. Configurations specify how a design
is "assembled" during the elaboration phase of simulation. Configurations actually consist
of two pieces: the library mapping and the configuration itself. The library mapping is used
at compile time to determine into which libraries the source files are to be compiled. Here
is an example of a simple library map file:
library work ../top.v;
library rtlLib lrm_ex_top.v;
library gateLib lrm_ex_adder.vg;
library aLib lrm_ex_adder.v;
The name of the library map file is arbitrary. You specify the library map file using the
-libmap argument to the vlog command (CR-358). Alternatively, you can specify the file
name as the first item on the vlog command line, and the compiler will read it as a library
map file.
The library map file must be compiled along with the Verilog source files. Multiple map
files are allowed but each must be preceded by the -libmap argument.
The library map file and the configuration can exist in the same or different files. If they
are separate, only the map file needs the -libmap argument. The configuration is treated as
any other Verilog source file.
generate
if (p)
integer x = 1;
else
real x = 2.0;
endgenerate
initial $display(x);
endmodule
This code sample is legal under 2001 rules. However, it is illegal under the proposed 2005
rules and will cause an error in ModelSim. Under the new rules, you cannot hierarchically
reference a name in an anonymous scope from outside that scope. In the example above, x
does not propagate its visibility upwards, and each condition alternative is considered to be
an anonymous scope.
To fix the code such that it will simulate properly in ModelSim, write it like this instead:
module m;
parameter p = 1;
if (p) begin:s
integer x = 1;
end
else begin:s
real x = 2.0;
end
initial $display(s.x);
endmodule
Since the scope is named in this example, normal hierarchical resolution rules apply and
the code is fine.
Note too that the keywords generate - endgenerate are optional under the new rules and
are excluded in the second example.
Note: Gate-level designs should generally not be optimized with vopt. See "Optimizing
gate-level designs" (UM-127) below for more details.
Example
The following is an example invocation of vlog and vopt and the resulting transcript
messages:
% vlog -vopt cpu_rtl.v
-- Compiling module fp_unit
-- Compiling module mult_56
-- Compiling module testbench
-- Compiling module cpu
-- Compiling module i_unit
-- Compiling module mem_mux
-- Compiling module memory32
-- Compiling module op_unit
The "Analyzing design..." message indicates that ModelSim is building the design
hierarchy, propagating parameters, and analyzing design object usage. This information is
then used to generate module code optimized for the specific design.
The vopt command creates an optimized version of the design in the working directory
using the name you specify with the -o argument. The entire library structure of the
optimized design is stored there, so you can run vsim (CR-373) directly on the name you
specified:
% vsim mydesign
# Loading work.testbench(fast)
# Loading work.cpu(fast)
You can see optimized designs in the GUI or with vdir (CR-328), delete them with vdel (CR-
327),
etc. For example, a vdir command shows something like the following:
OPTIMIZED DESIGN opt1
<spec> Meaning
If your design uses PLI applications that look for object handles in the design hierarchy,
then it is likely that you will need to use the +acc option. For example, the built-in
$dumpvars system task is an internal PLI application that requires handles to nets and
registers so that it can call the PLI routine acc_vcl_add() to monitor changes and dump the
values to a VCD file. This requires that access is enabled for the nets and registers on which
it operates. Suppose you want to dump all nets and registers in the entire design, and that
you have the following $dumpvars call in your testbench (no arguments to $dumpvars
means to dump everything in the entire design):
initial $dumpvars;
Then you need to optimize your design as follows to enable net and register access for all
modules in the design:
% vopt +acc=rn testbench
As another example, suppose you only need to dump nets and registers of a particular
instance in the design (the first argument of 1 means to dump just the variables in the
instance specified by the second argument):
initial $dumpvars(1, testbench.u1);
Then you need to compile your design as follows (assuming testbench.u1 refers to the
module design):
% vopt +acc=rn+design testbench
Finally, suppose you need to dump everything in the children instances of testbench.u1 (the
first argument of 0 means to also include all children of the instance):
initial $dumpvars(0, testbench.u1);
In these cases, you should optimize the entire design with vopt.
Several switches to vlog can be used to further increase optimizations on gate-level designs.
The +nocheck arguments are described in the Command Reference under the vlog
command (CR-358).
You can use the write cell_report command (CR-421) and the -debugCellOpt argument to
the vlog command (CR-358) to obtain information about which cells have and have not been
optimized. write cell_report produces a text file that lists all modules. Modules with
"(cell)" following their names are optimized cells. For example,
Module: top
Architecture: fast
In this case, both top and bottom were compiled with -fast, but top was not optimized and
bottom was.
The -debugCellOpt argument is used with -fast when compiling the cell library. Using this
argument produces output in the Transcript pane that identifies why certain cells were not
optimized.
After the simulator loads the top-level modules, it iteratively loads the instantiated modules
and UDPs in the design hierarchy, linking the design together by connecting the ports and
resolving hierarchical references. By default all modules and UDPs are loaded from the
library named work. Modules and UDPs from other libraries can be specified using the -L
or -Lf arguments to vsim (see "Library usage" (UM-117) for details).
On successful loading of the design, the simulation time is set to zero, and you must enter
a run command to begin simulation. Commonly, you enter run -all to run until there are
no more simulation events or until $finish is executed in the Verilog code. You can also
run for specific time periods (e.g., run 100 ns). Enter the quit command to exit the
simulator.
The first number is the time units and the second number is the time precision. The directive
above causes time values to be read as ns and to be rounded to the nearest 100 ps.
Module 1 Module 2
`timescale 1 ns / 10 ps module mod2 (set);
endmodule
If you invoke vsim as vsim mod2 mod1 then Module 1 sets the simulator resolution to 10 ps.
Module 2 has no timescale directive, so the time units default to the simulator resolution,
in this case 10 ps. If you watched /mod1/set and /mod2/set in the Wave window, you’d see
that in Module 1 it transitions every 1.55 ns as expected (because of the 1 ns time unit in
the timescale directive). However, in Module 2, set transitions every 20 ps. That’s because
the delay of 1.55 in Module 2 is read as 15.5 ps and is rounded up to 20 ps.
In such cases ModelSim will issue the following warning message during elaboration:
** Warning: (vsim-3010) [TSCALE] - Module 'mod1' has a `timescale directive
in effect, but previous modules do not.
If you invoke vsim as vsim mod1 mod2, the simulation results would be the same but
ModelSim would produce a different warning message:
** Warning: (vsim-3009) [TSCALE] - Module 'mod2' does not have a `timescale
directive in effect, but previous modules do.
module foo;
initial
#12.536 $display
The list below shows three possibilities for -t and how the delays in the module would be
handled in each case:
• -t not set
The delay will be rounded to 12.5 as directed by the module’s ‘timescale directive.
• -t is set to 1 fs
The delay will be rounded to 12.5. Again, the module’s precision is determined by the
‘timescale directive. ModelSim does not override the module’s precision.
• -t is set to 1 ns
The delay will be rounded to 12. The module’s precision is determined by the -t setting.
ModelSim has no choice but to round the module’s time values because the entire
simulation is operating at 1 ns.
Event queues
Section 5 of the IEEE Std 1364-1995 LRM defines several event queues that determine the
order in which events are evaluated. At the current simulation time, the simulator has the
following pending events:
• active events
• inactive events
• non-blocking assignment update events
• monitor events
• future events
- inactive events
- non-blocking assignment update events
The LRM dictates that events are processed as follows – 1) all active events are processed;
2) the inactive events are moved to the active event queue and then processed; 3) the
non-blocking events are moved to the active event queue and then processed; 4) the monitor
events are moved to the active queue and then processed; 5) simulation advances to the next
time where there is an inactive event or a non-blocking assignment update event.
Within the active event queue, the events can be processed in any order, and new active
events can be added to the queue in any order. In other words, you cannot control event
order within the active queue. The example below illustrates potential ramifications of this
situation.
Say you have these four statements:
1 always@(q) p = q;
The tables below show two of the many valid evaluations of these statements. Evaluation
events are denoted by a number where the number is the statement to be evaluated. Update
events are denoted <name>(old->new) where <name> indicates the reg being updated and
new is the updated value.
Table 1: Evaluation 1
Event being processed Active event queue
q(0 → 1)
q(0 → 1) 1, 2
1 p(0 → 1), 2
p(0 → 1) 3, 2
3 clk(0 → 1), 2
clk(0 → 1) 4, 2
4 2
2 p2(1 → 0)
p2(1 → 0) 3
3 clk(1 → 0)
clk(1 → 0) <empty>
Table 2: Evaluation 2
Event being processed Active event queue
q(0 → 1)
q(0 → 1) 1, 2
1 p(0 → 1), 2
p(0 → 1) 3, p2(1 → 0)
p2(1 → 0) 3
3 <empty> (clk doesn’t change)
Again, both evaluations are valid. However, in Evaluation 1, clk has a glitch on it; in
Evaluation 2, clk doesn’t. This indicates that the design has a zero-delay race condition on
clk.
Blocking assignments
Blocking assignments place an event in the active, inactive, or future queues depending on
what type of delay they have:
• a blocking assignment without a delay goes in the active queue
• a blocking assignment with an explicit delay of 0 goes in the inactive queue
• a blocking assignment with a non-zero delay goes in the future queue
Non-blocking assignments
A non-blocking assignment goes into either the non-blocking assignment update event
queue or the future non-blocking assignment update event queue. (Non-blocking
assignments with no delays and those with explicit zero delays are treated the same.)
Non-blocking assignments should be used only for outputs of flip-flops. This insures that
all outputs of flip-flops do not change until after all flip-flops have been evaluated.
Attempting to use non-blocking assignments in combinational logic paths to remove race
conditions may only cause more problems. (In the preceding example, changing all
statements to non-blocking assignments would not remove the race condition.) This
includes using non-blocking assignments in the generation of gated clocks.
The following is an example of how to properly use non-blocking assignments.
gen1: always @(master)
clk1 = master;
If written this way, a value on d1 always takes two clock cycles to get from d1 to q2.
If you change clk1 = master and clk2 = clk1 to non-blocking assignments or q2 <= q1 and
q1 <= d1 to blocking assignments, then d1 may get to q2 is less than two clock cycles.
ModelSim helps you track down event order dependencies with the following compiler
arguments: -compat, -hazards, and -keep_delta.
See the vlog command (CR-358) for descriptions of -compat and -keep_delta.
Hazard detection
The -hazard argument to vsim (CR-373) detects event order hazards involving simultaneous
reading and writing of the same register in concurrently executing processes. vsim detects
the following kinds of hazards:
• WRITE/WRITE:
Two processes writing to the same variable at the same time.
• READ/WRITE:
One process reading a variable at the same time it is being written to by another process.
ModelSim calls this a READ/WRITE hazard if it executed the read first.
• WRITE/READ:
Same as a READ/WRITE hazard except that ModelSim executed the write first.
vsim issues an error message when it detects a hazard. The message pinpoints the variable
and the two processes involved. You can have the simulator break on the statement where
the hazard is detected by setting the break on assertion level to Error.
To enable hazard detection you must invoke vlog (CR-358) with the -hazards argument
when you compile your source code and you must also invoke vsim with the -hazards
argument when you simulate.
Example
d violation 5 3
region
0
clk
ModelSim calculates the delay for signal d_dly as 4 time units instead of 3. It does this to
prevent d_dly and clk_dly from occurring simultaneously when a violation isn’t reported.
ModelSim accepts negative limit checks by default, unlike current versions of Verilog-XL.
To match Verilog-XL default behavior (i.e., zeroing all negative timing check limits), use
the +no_neg_tcheck argument to vsim (CR-373).
+pulse_e_style_onevent
+pulse_int_e/<percent>
+pulse_int_r/<percent>
+pulse_r/<percent>
+sdf_nocheck_celltype
+sdf_verbose
+show_cancelled_e
+transport_int_delays
+transport_path_delays
+typdelays
1 If timing for your design is fixed, include all timing data when you create the elaboration
file (using the -sdf<type> instance=<filename> argument). If your timing is not fixed
in a Verilog design, you’ll have to use $sdf_annotate system tasks. Note that use of
$sdf_annotate causes timing to be applied after elaboration.
2 Apply all normal vsim arguments when you create the elaboration file. Some arguments
(primarily related to stimulus) may be superseded later during loading of the elaboration
file (see "Modifying stimulus" (UM-140) below).
3 Load the elaboration file along with any arguments that modify the stimulus (see below).
Important: Elaboration files can be created in command-line mode only. You cannot
create an elaboration file while running the ModelSim GUI.
Modification of an argument that was specified at elaboration file creation, in most cases,
causes the previous value to be replaced with the new value. Usage of the -quiet argument
at elaboration load causes the mode to be toggled from its elaboration creation setting.
All other vsim arguments must be specified when you create the elaboration file, and they
cannot be used when you load the elaboration file.
Important: The elaboration file must be loaded under the same environment in which it
was created. The same environment means the same hardware platform, the same OS
and patch version, and the same version of any PLI/FLI code loaded in the simulation.
Modifying stimulus
A primary use of elaboration files is repeatedly simulating the same design with different
stimulus. The following mechanisms allow you to modify stimulus for each run.
• Use of the change command to modify parameters or generic values. This affects values
only; it has no effect on triggers, compiler directives, or generate statements that
reference either a generic or parameter.
• Use of the -filemap_elab <HDLfilename>=<NEWfilename> argument to establish a
map between files named in the elaboration file. The <HDLfilename> file name, if it
appears in the design as a file name (for example, a VHDL FILE object as well as some
Verilog sysfuncs that take file names), is substituted with the <NEWfilename> file
name. This mapping occurs before environment variable expansion and can’t be used to
redirect stdin/stdout.
• VCD stimulus files can be specified when you load the elaboration file. Both vcdread and
vcdstim are supported. Specifying a different VCD file when you load the elaboration file
supersedes a stimulus file you specify when you create the elaboration file.
• In Verilog, the use of +args which are readable by the PLI routine mc_scan_plusargs().
+args values specified when you create the elaboration file are superseded by +args
values specified when you load the elaboration file.
Syntax
See the vsim command (CR-373) for details on -elab, -elab_cont, -elab_defer_fli,
-compress_elab, -filemap_elab, and -load_elab.
Example
Upon first simulating the design, use vsim -elab <filename>
<library_name.design_unit> to create an elaboration file that will be used in subsequent
simulations.
In subsequent simulations you simply load the elaboration file (rather than the design) with
vsim -load_elab <filename>.
To change the stimulus without recoding, recompiling, and reloading the entire design,
Modelsim allows you to map the stimulus file (or files) of the original design unit to an
alternate file (or files) with the -filemap_elab switch. For example, the VHDL code for
initiating stimulus might be:
FILE vector_file : text IS IN "vectors";
Checkpoint exclusions
You can also control checkpoint compression using the modelsim.ini file in the [vsim]
section (use the same 0 or 1 switch):
[vsim]
CheckpointCompressMode = <switch>
Cell libraries
Model Technology passed the ASIC Council’s Verilog test suite and achieved the "Library
Tested and Approved" designation from Si2 Labs. This test suite is designed to ensure
Verilog timing accuracy and functionality and is the first significant hurdle to complete on
the way to achieving full ASIC vendor support. As a consequence, many ASIC and FPGA
vendors’ Verilog cell libraries are compatible with ModelSim Verilog.
The cell models generally contain Verilog "specify blocks" that describe the path delays
and timing constraints for the cells. See section 13 in the IEEE Std 1364-1995 for details
on specify blocks, and section 14.5 for details on timing constraints. ModelSim Verilog
fully implements specify blocks and timing constraints as defined in IEEE Std 1364 along
with some Verilog-XL compatible extensions.
Delay modes
Verilog models may contain both distributed delays and path delays. The delays on
primitives, UDPs, and continuous assignments are the distributed delays, whereas the port-
to-port delays specified in specify blocks are the path delays. These delays interact to
determine the actual delay observed. Most Verilog cells use path delays exclusively, with
the distributed delays set to zero. For example,
module and2(y, a, b);
input a, b;
output y;
and(y, a, b);
specify
(a => y) = 5;
(b => y) = 5;
endspecify
endmodule
In the above two-input "and" gate cell, the distributed delay for the "and" primitive is zero,
and the actual delays observed on the module ports are taken from the path delays. This is
typical for most cells, but a complex cell may require non-zero distributed delays to work
properly. Even so, these delays are usually small enough that the path delays take priority
over the distributed delays. The rule is that if a module contains both path delays and
distributed delays, then the larger of the two delays for each path shall be used (as defined
by the IEEE Std 1364). This is the default behavior, but you can specify alternate delay
modes with compiler directives and arguments. These arguments and directives are
compatible with Verilog-XL. Compiler delay mode arguments take precedence over delay
mode directives in the source code.
$time
$dist_uniform $skew
$random $widtha
$removal
$recrem
a.Verilog-XL ignores the threshold argument even though it is part of the Verilog
spec. ModelSim does not ignore this argument. Be careful that you don’t set the
threshold argument greater-than-or-equal to the limit argument as that essentially dis-
ables the $width check. Note too that you cannot override the threshold argument via
SDF annotation.
$strobeo $sync$nand$plane
$write $sync$or$plane
$writeb $sync$nor$plane
$writeh
$writeo
$fmonitorh $swriteo
$fmonitoro $ungetc
The following system tasks and functions are also provided for compatibility with Verilog-
XL; they are not described in the IEEE Std 1364.
$deposit(variable, value);
This system task sets a Verilog register or net to the specified value. variable is the
register or net to be changed; value is the new value for the register or net. The value
remains until there is a subsequent driver transaction or another $deposit task for the
same register or net. This system task operates identically to the ModelSim
force -deposit command.
$disable_warnings(“<keyword>”[,<module_instance>...]);
This system task instructs ModelSim to disable warnings about timing check violations
or triregs that acquire a value of ‘X’ due to charge decay. <keyword> may be decay or
timing. You can specify one or more module instance names. If you don’t specify a
module instance, ModelSim disables warnings for the entire simulation.
$enable_warnings(“<keyword>”[,<module_instance>...]);
This system task enables warnings about timing check violations or triregs that acquire a
value of ‘X’ due to charge decay. <keyword> may be decay or timing. You can specify
one or more module instance names. If you don’t specify a module_instance, ModelSim
enables warnings for the entire simulation.
$system("<operating system shell command>");
This system task executes the specified operating system shell command and displays the
result. For example, to list the contents of the working directory on Unix:
$system("ls");
The following system tasks are extended to provide additional functionality for negative
timing constraints and an alternate method of conditioning, as in Verilog-XL.
$recovery(reference event, data_event, removal_limit, recovery_limit,
[notifier], [tstamp_cond], [tcheck_cond], [delayed_reference],
[delayed_data])
The $recovery system task normally takes a recovery_limit as the third argument and an
optional notifier as the fourth argument. By specifying a limit for both the third and
fourth arguments, the $recovery timing check is transformed into a combination removal
and recovery timing check similar to the $recrem timing check. The only difference is
that the removal_limit and recovery_limit are swapped.
$setuphold(clk_event, data_event, setup_limit, hold_limit, [notifier],
[tstamp_cond], [tcheck_cond], [delayed_clk], [delayed_data])
The tstamp_cond argument conditions the data_event for the setup check and the
clk_event for the hold check. This alternate method of conditioning precludes specifying
conditions in the clk_event and data_event arguments.
The tcheck_cond argument conditions the data_event for the hold check and the
clk_event for the setup check. This alternate method of conditioning precludes specifying
conditions in the clk_event and data_event arguments.
The delayed_clk argument is a net that is continuously assigned the value of the net
specified in the clk_event. The delay is non-zero if the setup_limit is negative, zero
otherwise.
The delayed_data argument is a net that is continuously assigned the value of the net
specified in the data_event. The delay is non-zero if the hold_limit is negative, zero
otherwise.
The delayed_clk and delayed_data arguments are provided to ease the modeling of
devices that may have negative timing constraints. The model's logic should reference
the delayed_clk and delayed_data nets in place of the normal clk and data nets. This
ensures that the correct data is latched in the presence of negative constraints. The
simulator automatically calculates the delays for delayed_clk and delayed_data such that
the correct data is latched as long as a timing constraint has not been violated. See
"Negative timing check limits" (UM-136) for more details.
The following system tasks are Verilog-XL system tasks that are not implemented in
ModelSim Verilog, but have equivalent simulator commands.
$input("filename")
This system task reads commands from the specified filename. The equivalent simulator
command is do <filename>.
$list[(hierarchical_name)]
This system task lists the source code for the specified scope. The equivalent
functionality is provided by selecting a module in the structure pane of the Workspace.
The corresponding source code is displayed in a Source window.
$reset
This system task resets the simulation back to its time 0 state. The equivalent simulator
command is restart.
$restart("filename")
This system task sets the simulation to the state specified by filename, saved in a previous
call to $save. The equivalent simulator command is restore <filename>.
$save("filename")
This system task saves the current simulation state to the file specified by filename. The
equivalent simulator command is checkpoint <filename>.
$scope(hierarchical_name)
This system task sets the interactive scope to the scope specified by hierarchical_name.
The equivalent simulator command is environment <pathname>.
$showscopes
This system task displays a list of scopes defined in the current interactive scope. The
equivalent simulator command is show.
$showvars
This system task displays a list of registers and nets defined in the current interactive
scope. The equivalent simulator command is show.
Compiler directives
ModelSim Verilog supports all of the compiler directives defined in the IEEE Std 1364,
some Verilog-XL compiler directives, and some that are proprietary.
Many of the compiler directives (such as `timescale) take effect at the point they are
defined in the source code and stay in effect until the directive is redefined or until it is reset
to its default by a `resetall directive. The effect of compiler directives spans source files,
so the order of source files on the compilation command line could be significant. For
example, if you have a file that defines some common macros for the entire design, then
you might need to place it first in the list of files to be compiled.
The `resetall directive affects only the following directives by resetting them back to their
default settings (this information is not provided in the IEEE Std 1364):
`celldefine
‘default_decay_time
`default_nettype
`delay_mode_distributed
`delay_mode_path
`delay_mode_unit
`delay_mode_zero
`protected
`timescale
`unconnected_drive
`uselib
`delay_mode_unit
This directive sets path delays to zero and non-zero distributed delays to one time unit.
See "Delay modes" (UM-144) for details.
`delay_mode_zero
This directive sets path delays and distributed delays to zero. See "Delay modes" (UM-
144) for details.
`uselib
This directive is an alternative to the -v, -y, and +libext source library compiler
arguments. See "Verilog-XL `uselib compiler directive" (UM-120) for details.
The following Verilog-XL compiler directives are silently ignored by ModelSim Verilog.
Many of these directives are irrelevant to ModelSim Verilog, but may appear in code being
ported from Verilog-XL.
`accelerate
`autoexpand_vectornets
`disable_portfaults
`enable_portfaults
`expand_vectornets
`noaccelerate
`noexpand_vectornets
`noremove_gatenames
`noremove_netnames
`nosuppress_faults
`remove_gatenames
`remove_netnames
`suppress_faults
However, you can override this automatic behavior using mti_sparse with a value:
(* mti_sparse = 0 *) reg mem[0:2047]; // will *not* be marked as sparse even
though SparseMemThreshold = 2048
The write report command (CR-426) lists summary information about the design, including
sparse memory handling. You would issue this command if you aren’t certain whether a
memory was successfully implemented as sparse or not. For example, you might add a /
*sparse*/ metacomment above a multi-D SystemVerilog memory, which we don't
support. In that case, the simulation will function correctly, but ModelSim will use a non-
sparse implementation of the memory.
Limitations
There are certain limitations that exist with sparse memories:
• Sparse memories can have only one packed dimension. For example:
reg [0:3] [2:3] mem [0:1023]
cannot be processed as a sparse memory unless the design has been optimized with the
vopt command (CR-371). In optimized designs, the memory will be implemented as a
sparse memory, and all parameter overrides to that MYDEPTH parameter will be treated
correctly.
6 - SystemC simulation
Chapter contents
Introduction . . . . . . . . . . . . . . . UM-160
Supported platforms and compiler versions . . . . . . . UM-161
Building gcc with custom configuration options . . . . . UM-161
HP Limitations for SystemC . . . . . . . . . . UM-162
Note: The functionality described in this chapter requires a systemc license feature in
your ModelSim license file. Please contact your Mentor Graphics sales representative if
you currently do not have such a feature.
Introduction
This chapter describes how to compile and simulate SystemC designs with ModelSim.
ModelSim implements the SystemC language based on the Open SystemC Initiative
(OSCI) SystemC 2.0.1 reference simulator. It is recommended that you obtain the OSCI
functional specification, or the latest version of the SystemC Language Reference Manual
as a reference manual. Visit http://www.systemc.org for details.
In addition to the functionality described in the OSCI specification, ModelSim for SystemC
includes the following features:
• Single common Graphic Interface for SystemC and HDL languages.
• Extensive support for mixing SystemC, VHDL, and Verilog in the same design (SDF
annotation for HDL only). For detailed information on mixing SystemC with HDL see
Chapter 7 - Mixed-language simulation.
Important: ModelSim SystemC has been tested with the gcc versions available from
ftp.model.com/pub/gcc. Customized versions of gcc may cause problems. We strongly
encourage you to download and use the gcc versions available on our FTP site (login as
anonymous).
Linux none
HP-UX N/A
If you don't have a GNU binutils2.14 assembler and linker handy, you can use the as and
ld programs distributed with ModelSim. They are located inside the built-in gcc in directory
<install_dir>/modeltech/gcc-3.2-<mtiplatform>/lib/gcc-lib/<gnuplatform>/3.2.
By default ModelSim also uses the following options when configuring built-in gcc.
• --disable-nls
• --enable-languages=c,c++
These are not mandatory, but they do reduce the size of the gcc installation.
1 Create and map the working design library with the vlib and vmap statements, as
appropriate to your needs.
3 Analyze the SystemC source using sccom (CR-254). sccom invokes the native C++
compiler to create the C++ object files in the design library.
See "Using sccom vs. raw C++ compiler" (UM-170) for information on when you are
required to use sccom vs. another C++ compiler.
4 Perform a final link of the C++ source using sccom -link (UM-172). This process creates
a shared object file in the current work library which will be loaded by vsim at runtime.
sccom -link must be re-run before simulation if any new sccom compiles were
performed.
6 Simulate the design using the run command, entered at the vsim command prompt.
7 Debug the design using ModelSim GUI features, including the Source and Wave
windows.
This creates a library named work. By default, compilation results are stored in the work
library.
The work library is actually a subdirectory named work. This subdirectory contains a
special file named _info. Do not create libraries using UNIX commands – always use the
vlib command (CR-356).
See "Design libraries" (UM-57) for additional information on working with libraries.
Replacing the sc_start() function with the run command and options
ModelSim uses the run command and its options in place of the sc_start() function. If
sc_main() has multiple sc_start() calls mixed in with the testbench code, then use an
SC_THREAD() with wait statements to emulate the same behavior. An example of this is
shown below.
Example 1
The following is a simple example of how to convert sc_main to a module and elaborate it
with vsim.
SC_MODULE_EXPORT(mytop);
Example 2
This next example is slightly more complex, illustrating the use of sc_main() and signal
assignments, and how you would get the same behavior using ModelSim.
SC_MODULE_EXPORT(new_top);
Example 3
One last example illustrates the correct way to modify a design using an SCV transaction
database. ModelSim requires that the transaction database be created before calling the
constructors on the design subelements. The example is as follows:
SC_MODULE_EXPORT(new_top);
Take care to preserve the order of functions called in sc_main() of the original code.
Sub-elements cannot be placed in the initializer list, since the constructor body must be
executed prior to their construction. Therefore, the sub-elements must be made pointer
types, created with "new" in the SC_CTOR() module.
SC_CTOR(mytop)
: mysig("mysig"),
mod("mod")
{
mod.outp(mysig);
}
};
SC_MODULE_EXPORT(top);
sc_start(100, SC_NS);
}
#endif
You can type verror 3197 at the vsim command prompt and get details about what caused
the error and how to fix it.
1 You must compile all code that references SystemC types or objects using sccom (CR-
254).
2 When using sccom, you should not use the -I compiler option to point the compiler at
any search directories containing OSCI or any other vendor supplied SystemC header
files. sccom does this for you accurately and automatically.
3 If you do use the raw C++ compiler to compile C/C++ functionality into archives or
shared objects, you must then link your design using the -L and -l options with the sccom
-link command. These options effectively pull the non-SystemC C/C++ code into a
simulation image that is used at runtime.
Failure to follow the above rules can result in link-time or elaboration-time errors due to
mismatches between the OSCI or any other vendor supplied SystemC header files and the
ModelSim SystemC header files.
1 The -fPIC option to g++ should be used during compilation with sccom.
2 For C++ code, you must use the built-in g++ delivered with ModelSim, or (if using a
custom g++) use the one you built and specified with the CppPath .ini variable.
Otherwise binary incompatibilities may arise between code compiled by sccom and code
compiled by raw g++.
1 For C++ code, you should use the +Z and -AA options during compilation
You can specialize the module by setting T = int, thereby removing the template, as
follows:
class top : public sc_module
{
sc_signal<int> sig 1;
.
.
.
};
Or, alternatively, you could write a wrapper to be used over the template module:
class modelsim_top : public sc_module
{
top<int> actual_top;
.
.
.
};
SC_MODULE_EXPORT(modelsim_top);
sccom -link
The sccom -link command collects the object files created in the different design libraries,
and uses them to build a shared library (.so) in the current work library or the library
specified by the -work option. If you have changed your SystemC source code and
recompiled it using sccom, then you must relink the design by running sccom -link before
invoking vsim. Otherwise, your changes to the code are not recognized by the simulator.
Remember that any dependent .a or .o files should be listed on the sccom -link command
line before the .a or .o on which it depends. For more details on dependencies and other
syntax issues, see sccom (CR-254).
When the GUI comes up, you can expand the hierarchy of the design to view the SystemC
modules. SystemC objects are denoted by green icons (see "Design object icons and their
meaning" (GR-12) for more information).
To simulate from a command shell, without the GUI, invoke vsim with the -c option:
vsim -c <top_level_module>
Running simulation
Run the simulation using the run (CR-252) command or select one of the Simulate > Run
options from the menu bar.
a simulator resolution of 10ps would be fine. No rounding off of the ones digits in the time
units would occur. However, a specification of:
sc_wait(9, SC_PS);
would require you to set the resolution limit to 1ps in order to avoid inaccuracies caused by
rounding.
1 Constructors
2 before_end_of_elaboration ()
3 end_of_elaboration ()
4 start_of_simulation ()
5 end_of_simulation ()
6 Destructors
Usage of callbacks
The start_of_simulation() callback is used to initialize any state-based code. The
corresponding cleanup code should be placed in the end_of_simulation() callback. These
callbacks are only called during simulation by vsim and thus, are safe.
If you have a design in which some state-based code must be placed in the constructor,
destructor, or the elaboration callbacks, you can use the mti_IsVoptMode() function to
determine if the elaboration is being run by vopt (CR-371). You can use this function to
prevent vopt from executing any state-based code.
Types (<type>) of the objects which may be viewed for debugging are the following:
Types
bool, sc_bit
sc_logic
sc_bv<width>
sc_lv<width>
sc_int<width>
sc_uint<width>
sc_fix
sc_fix_fast
sc_fixed<W,I,Q,O,N>
sc_fixed_fast<W,I,Q,O,N>
sc_ufix
sc_ufix_fast
sc_ufixed
sc_ufixed_fast
sc_signed
sc_unsigned
char, unsigned char
int, unsigned int
short, unsigned short
long, unsigned long
sc_bigint<width>
sc_biguint<width>
sc_ufixed<W,I,Q,O,N>
short, unsigned short
long long, unsigned long long
float
double
enum
pointer
class
struct
union
bit_fields
Waveform compare
Waveform compare supports the viewing of SystemC signals and variables. You can
compare SystemC objects to SystemC, Verilog or VHDL objects.
For pure SystemC compares, you can compare any two signals that match type and size
exactly; for C/C++ types and some SystemC types, sign is ignored for compares. Thus, you
can compare char to unsigned char or sc_signed to sc_unsigned. All SystemC fixed-point
types may be mixed as long as the total number of bits and the number of integer bits match.
The number of elements must match for vectors; specific indexes are ignored.
Source-level debug
In order to debug your SystemC source code, you must compile the design for debug using
the -g C++ compiler option. You can add this option directly to the sccom (CR-254)
command line on a per run basis, with a command such as:
sccom mytop -g
Or, if you plan to use it every time you run the compiler, you can specify it in the
modelsim.ini file with the SccomCppOptions variable. See "[sccom] SystemC compiler
control variables" (UM-528) for more information.
The source code debugger, C Debug (UM-399), is automatically invoked when the design is
compiled for debug in this way.
You can set breakpoints in a Source window, and single-step through your SystemC/C++
source code. .
The gdb debugger has a known bug that makes it impossible to set breakpoints reliably in
constructors or destructors. Try to avoid setting breakpoints in constructors of SystemC
objects; it may crash the debugger.
You can view and expand SystemC objects in the Objects pane and processes in the Active
Processes pane.
is equivalent to:
sc_signal <sc_lv<3>> a;
for debug purposes. ModelSim shows one signal - object "a" - in both cases.
The following aggregate
sc_signal <float> fbus [6];
Viewing FIFOs
In ModelSim, the values contained in an sc_fifo appear in a definite order. The top-most or
left-most value is always the next to be read from the FIFO. Elements of the FIFO that are
not in use are not displayed.
Example of a signal where the FIFO has five elements:
# examine f_char
# {}
VSIM 4> # run 10
VSIM 6> # examine f_char
# A
VSIM 8> # run 10
VSIM 10> # examine f_char
# {A B}
VSIM 12> # run 10
VSIM 14> # examine f_char
# {A B C}
VSIM 16> # run 10
VSIM 18> # examine f_char
# {A B C D}
VSIM 20> # run 10
VSIM 22> # examine f_char
# {A B C D E}
VSIM 24> # run 10
VSIM 26> # examine f_char
# {B C D E}
VSIM 28> # run 10
VSIM 30> # examine f_char
# {C D E}
VSIM 32> # run 10
VSIM 34> # examine f_char
# {D E}
• add a define statement to the C++ source code before the inclusion of the systemc.h, as
shown below:
#define SC_INCLUDE_FX
#include "systemc.h"
Phase callback
The following functions are supported for phase callbacks:
• before_end_of_elaboration()
• start_of_simulation()
• end_of_simulation()
For more information regarding the use of these functions, see "Initialization and cleanup
of SystemC state-based code" (UM-175).
argc = sc_argc();
argv = sc_argv();
/home/cmg/newport2_systemc/chip/vhdl/work/systemc.so: symbol
_Z28host_respond_to_vhdl_requestPm:
Missing definition
If the undefined symbol is a C function in your code or a library you are linking with, be
sure that you declared it as an extern "C" function:
extern "C" void myFunc();
This should appear in any header files include in your C++ sources compiled by sccom. It
tells the compiler to expect a regular C function; otherwise the compiler decorates the name
for C++ and then the symbol can't be found.
Also, be sure that you actually linked with an object file that fully defines the symbol. You
can use the "nm" utility on Unix platforms to test your SystemC object files and any
libraries you link with your SystemC sources. For example, assume you ran the following
commands:
sccom test.cpp
sccom -link libSupport.a
If there is an unresolved symbol and it is not defined in your sources, it should be correctly
defined in any linked libraries:
nm libSupport.a | grep "mySymbol"
Missing type
When you get errors during design elaboration, be sure that all the items in your SystemC
design hierarchy, including parent elements, are declared in the declarative region of a
module. If not, sccom ignores them.
For example, we have a design containing SystemC over VHDL. The following declaration
of a child module "test" inside the constructor module of the code is not allowed and will
produce an error:
SC_MODULE(Export)
{
SC_CTOR(Export)
{
test *testInst;
testInst = new test("test");
}
};
The error results from the fact that the SystemC parse operation will not see any of the
children of "test". Nor will any debug information be attached to it. Thus, the signal has no
type information and can not be bound to the VHDL port.
The solution is to move the element declaration into the declarative region of the module.
and
sccom liblocal.a -link
The first command ensures that your SystemC object files are seen by the linker before the
library "liblocal.a" and the second command ensures that "liblocal.a" is seen first. Some
linkers can look for undefined symbols in libraries that follow the undefined reference
while others can look both ways. For more information on command syntax and
dependencies, see sccom (CR-254).
7 - Mixed-language simulation
Chapter contents
Usage flow for mixed-language simulations . . . . . . . UM-189
Separate compilers, common design libraries . . . . . . . UM-190
Access limitations in mixed-language designs . . . . . UM-190
Optimizing mixed designs . . . . . . . . . . UM-190
Simulator resolution limit . . . . . . . . . . . UM-191
Runtime modeling semantics . . . . . . . . . . UM-191
Hierarchical references in mixed HDL/SystemC designs. . . UM-192
ModelSim single-kernel simulation allows you to simulate designs that are written in
VHDL, Verilog, and SystemC (not all ModelSim versions support all languages). The
boundaries between languages are enforced at the level of a design unit. This means that
although a design unit itself must be entirely of one language type, it may instantiate design
units from another language. Any instance in the design hierarchy may be a design unit
from another language without restriction.
1 Analyze HDL source code using vcom (CR-311) or vlog (CR-358) and SystemC C++
source code using sccom (CR-254). Analyze all modules in the design following order-
of-analysis rules.
• For SystemC designs with HDL instances:
Create a SystemC foreign module declaration for all Verilog and VHDL instances (see
"SystemC foreign module declaration" (UM-209) or (UM-217)).
• For Verilog/VHDL designs with SystemC instances:
Export any SystemC instances that will be directly instantiated by Verilog/VHDL using
the SC_MODULE_EXPORT macro. Exported SystemC modules can be instantianted
just as you would instantiate any Verilog/VHDL module or design unit.
3 If you have Verilog modules in your mixed design that you would like to optimize, you
would run the vopt command (CR-371) on the top-level design unit. See "Optimizing
mixed designs" (UM-190).
The argument (const char* name) is a full hierarchical path to an HDL signal or port. The
return value is "true" if the HDL signal is found and its type is compatible with the SystemC
signal type. See tables for Verilog "Data type mapping" (UM-197) and VHDL "Data type
mapping" (UM-200) to view a list of types supported at the mixed language boundary. If it
is a supported boundary type, it is supported for hierarchical references. If the function is
called during elaboration time, when the HDL signal has not yet elaborated, the function
always returns "true"; however, an error is issued before simulation starts.
Control
When a SystemC signal calls control_foreign_signal() on an HDL signal, the HDL signal
is considered a fanout of the SystemC signal. This means that every value change of the
SystemC signal is propagated to the HDL signal. If there is a pre-existing driver on the
HDL signal which has been controlled, the value is changed to reflect the SystemC signal’s
value. This value remains in effect until a subsequent driver transaction occurs on the HDL
signal, following the semantics of the force -deposit command.
Observe
When a SystemC signal calls observe_foreign_signal() on an HDL signal, the SystemC
signal is considered a fanout of the HDL signal. This means that every value change of the
HDL signal is propagated to the SystemC signal. If there is a pre-existing driver on the
SystemC signal which has been observed, the value is changed to reflect the HDL signal’s
value. This value remains in effect until a subsequent driver transaction occurs on the
SystemC signal, following the semantics of the force -deposit command.
Once a SystemC signal executes a control or observe on an HDL signal, the effect stays
throughout the whole simulation. Any subsequent control/observe on that signal will be an
error.
Example:
SC_MODULE(test_ringbuf)
{
sc_signal<bool> observe_sig;
sc_signal<sc_lv<4> > control_sig;
SC_CTOR(test_ringbuf)
{
ring_INST = new ringbuf("ring_INST", "ringbuf");
.....
observe_sig.observe_foreign_signal("/test_ringbuf/ring_INST/
block1_INST/buffers(0)");
control_sig.control_foreign_signal("/test_ringbuf/ring_INST/
block1_INST/sig");
}
};
Verilog parameters
integer integer
real real
string string
Verilog ports
The allowed VHDL types for ports connected to Verilog nets and for signals connected to
Verilog ports are:
bit
bit_vector
std_logic
std_logic_vector
vl_logic
vl_logic_vector
The vl_logic type is an enumeration that defines the full state set for Verilog nets, including
ambiguous strengths. The bit and std_logic types are convenient for most applications, but
the vl_logic type is provided in case you need access to the full Verilog state set. For
example, you may wish to convert between vl_logic and your own user-defined type. The
vl_logic type is defined in the vl_types package in the pre-compiled verilog library. This
library is provided in the installation directory along with the other pre-compiled libraries
(std and ieee). The source code for the vl_types package can be found in the files installed
with ModelSim. (See <install_dir>\modeltech\vhdl_src\verilog\vltypes.vhd.)
Verilog states
Verilog states are mapped to std_logic and bit as follows:
VHDL generics
When a scalar type receives a real value, the real is converted to an integer by truncating
the decimal portion.
Type time is treated specially: the Verilog number is converted to a time value according
to the ‘timescale directive of the module.
Physical and enumeration types receive a value that corresponds to the position number
indicated by the Verilog number. In VHDL this is equivalent to T'VAL(P), where T is the
type, VAL is the predefined function attribute that returns a value given a position number,
and P is the position number.
VHDL type bit is mapped to Verilog states as follows:
bit Verilog
'0' St0
'1' St1
std_logic Verilog
'U' StX
'X' StX
'0' St0
std_logic Verilog
'1' St1
'Z' HiZ
'W' PuX
'L' Pu0
'H' Pu1
'–' StX
SystemC Verilog
Port direction
Verilog port directions are mapped to SystemC as follows:
Verilog SystemC
bool Verilog
false St0
true St1
sc_bit Verilog
'0' St0
'1' St1
sc_logic Verilog
'0' St0
'1' St1
'Z' HiZ
'X' StX
SystemC has a more complex signal-level interconnect scheme than VHDL. Design units
are interconnected via hierarchical and primitive channels. An sc_signal<> is one type of
primitive channel. The following section discusses how various SystemC channel types
map to VHDL types when connected to each other across the language boundary.
SystemC VHDL
sc_logic std_logic
SystemC VHDL
VHDL SystemC
bool VHDL
false false
true true
sc_bit VHDL
'0' '0'
'1' '1'
sc_logic std_logic
'0' '0'
'1' '1'
'Z' 'Z'
'X' 'X'
Component declaration
A Verilog module that is compiled into a library can be referenced from a VHDL design as
though the module is a VHDL entity. Likewise, a Verilog configuration can be referenced
as though it were a VHDL configuration.
The interface to the module can be extracted from the library in the form of a component
declaration by running vgencomp (CR-330). Given a library and module name, vgencomp
(CR-330) writes a component declaration to standard output.
• The Verilog module, port, or parameter names are not unique unless case is preserved. In
this event, vgencomp (CR-330) behaves as if the module was compiled with the -93
switch for those names only.
If you use Verilog identifiers where the names are unique by case only, use the -93
argument when compiling mixed-language designs.
Examples
topmod topmod
TOPMOD topmod
TopMod topmod
top_mod top_mod
_topmod \_topmod\
\topmod topmod
\\topmod\ \topmod\
topmod topmod
TOPMOD \TOPMOD\
TopMod \TopMod\
top_mod top_mod
_topmod \_topmod\
\topmod topmod
\\topmod\ \topmod\
Generic clause
A generic clause is generated if the module has parameters. A corresponding generic is
defined for each parameter that has an initial value that does not depend on any other
parameters.
integer integer
real real
The default value of the generic is the same as the parameter's initial value.
Examples
Port clause
A port clause is generated if the module has ports. A corresponding VHDL port is defined
for each named Verilog port.
You can set the VHDL port type to bit, std_logic, or vl_logic. If the Verilog port has a
range, then the VHDL port type is bit_vector, std_logic_vector, or vl_logic_vector. If the
range does not depend on parameters, then the vector type will be constrained accordingly,
otherwise it will be unconstrained.
Examples
Configuration declarations are allowed to reference Verilog modules in the entity aspects
of component configurations. However, the configuration declaration cannot extend into a
Verilog instance to configure the instantiations within the Verilog module.
Note that a[3:0] is considered to be unnamed even though it is a full part-select. A common
mistake is to include the vector bounds in the port list, which has the undesired side effect
of making the ports unnamed (which prevents the user from connecting by name even in
an all-Verilog design).
Most modules having unnamed ports can be easily rewritten to explicitly name the ports,
thus allowing the module to be instantiated from VHDL. Consider the following example:
module m(y[1], y[0], a[1], a[0]);
output [1:0] y;
input [1:0] a;
endmodule
Here is the same module rewritten with explicit port names added:
module m(.y1(y[1]), .y0(y[0]), .a1(a[1]), .a0(a[0]));
output [1:0] y;
input [1:0] a;
endmodule
"Empty" ports
Verilog modules may have "empty" ports, which are also unnamed, but they are treated
differently from other unnamed ports. If the only unnamed ports are "empty", then the other
ports may still be connected to by name, as in the following example:
module m(a, , b);
input a, b;
endmodule
Although this module has an empty port between ports "a" and "b", the named ports in the
module can still be connected to from VHDL.
If the escaped identifier takes the form of one of the above and is not the name of a design
unit in the work library, then the instantiation is broken down as follows:
• library = mylib
• design unit = entity
• architecture = arch
Generic associations
Generic associations are provided via the module instance parameter value list. List the
values in the same order that the generics appear in the entity. Parameter assignment to
generics is not case sensitive.
The defparam statement is not allowed for setting generic values.
SDF annotation
A mixed VHDL/Verilog design can also be annotated with SDF. See "SDF for mixed
VHDL and Verilog designs" (UM-450) for more information.
Using scgenmod
After you have analyzed the design, you can generate a foreign module declaration with an
scgenmod command (CR-258) similar to the following:
scgenmod mod1
where mod1 is a Verilog module. A foreign module declaration for the specified module is
written to stdout.
Example #1
A sample Verilog module to be instantiated in a SystemC design is:
module vcounter (clock, topcount, count);
input clock;
input topcount;
output count;
reg count;
...
endmodule
The SystemC foreign module declaration for the above Verilog module is:
class counter : public sc_foreign_module {
public:
sc_in<bool> clock;
sc_in<sc_logic> topcount;
sc_out<sc_logic> count;
counter(sc_module_name nm)
: sc_foreign_module(nm, "lib.vcounter"),
clock("clock"),
topcount("topcount"),
count("count")
{}
};
where the constructor argument (dut) is the instance name of the Verilog module.
Example #2
Another variation of the SystemC foreign module declaration for the same Verilog module
might be:
class counter : public sc_foreign_module {
public:
...
...
...
{}
};
Example
Following the example shown above (UM-211), let’s see the parameter information that
would be passed to the SystemC foreign module declaration:
class counter : public sc_foreign_module {
public:
sc_in<bool> clk;
...
sc_in<bool> clk;
...
#endif
---------------------------------------------------------------------------
// test_ringbuf.h
#ifndef INCLUDED_TEST_RINGBUF
#define INCLUDED_TEST_RINGBUF
#include "ringbuf.h"
#include "string.h"
SC_MODULE(test_ringbuf)
{
sc_signal<sc_logic> iclock;
...
...
// Verilog module instance
ringbuf* chip;
SC_CTOR(test_ringbuf)
: iclock("iclock"),
...
...
{
const char* generic_list[3];
generic_list[0] = strdup("int_param=4");
generic_list[1] = strdup("real_param=2.6");
generic_list[2] = strdup("str_param=\"Hello\"");
// Enclose the string
// in double quotes
// Connect ports
chip->clock(iclock);
...
...
}
~test_ringbuf()
{
delete chip;
}
};
#endif
---------------------------------------------------------------------------
-----
// test_ringbuf.cpp
#include "test_ringbuf.h"
SC_MODULE_EXPORT(test_ringbuf);
--------------------------------------------------------------------
// ringbuf.v
initial begin
$display("int_param=%0d", int_param);
$display("real_param=%g", real_param);
$display("str_param=%s", str_param);
end
endmodule
---------------------------------------------------------------------------
• Port data type mapping must match exactly. See the table in "Data type mapping" (UM-
197).
Port associations may be named or positional. Use the same port names and port positions
that appear in the SystemC module declaration. Named port associations are case sensitive.
Parameter support is available as of the ModelSim 6.0 release. See "Parameter support for
Verilog instantiating SystemC" (UM-214).
SC_MODULE_EXPORT(transceiver);
format_char = 'a');
The first argument to sc_get_param defines the parameter name, the second defines the
parameter value. For retrieving string values, ModelSim also provides a third optional
argument, format_char. It is used to specify the format for displaying the retrieved string.
The format can be ASCII ("a" or "A"), binary ("b" or "b"), decimal ("d" or "d"), octal ("o"
or "O"), or hexadecimal ("h" or "H"). ASCII is the default.
Alternatively, you can use the following forms of the above functions in the constructor
initializer list:
int sc_get_int_param(const char* param_name);
double sc_get_real_param(const char* param_name);
sc_string sc_get_string_param(const char* param_name, char format_char =
'a');
---------------------------------------------------------------------------
// ringbuf.h
#ifndef INCLUDED_RINGBUF
#define INCLUDED_RINGBUF
#include
SC_MODULE(ringbuf)
{
public:
// Module ports
sc_in clock;
...
...
SC_CTOR(ringbuf)
: clock("clock"),
...
...
{
cout << "int_param="
<< sc_get_int_param("int_param") << endl;
cout << "real_param="
<< sc_get_real_param("real_param") << endl;
cout << "str_param="
<< (const char*)sc_get_string_param("str_param", 'a')
<< endl;
cout << "reg_param="
<< (const char*)sc_get_string_param("reg_param", 'b')
<< endl;
}
~ringbuf() {}
};
#endif
---------------------------------------------------------------------------
// ringbuf.cpp
#include "ringbuf.h"
SC_MODULE_EXPORT(ringbuf);
Using scgenmod
After you have analyzed the design, you can generate a foreign module declaration with an
scgenmod command similar to the following:
scgenmod mod1
Where mod1 is a VHDL entity. A foreign module declaration for the specified entity is
written to stdout.
Example
A sample VHDL design unit to be instantiated in a SystemC design is:
entity counter is
port (count : buffer bit_vector(8 downto 1);
clk : in bit;
reset : in bit);
end;
end only;
The SystemC foreign module declaration for the above VHDL module is:
class counter : public sc_foreign_module {
public:
sc_in<bool> clk;
sc_in<bool> reset;
sc_out<sc_logic> count;
counter(sc_module_name nm)
: sc_foreign_module(nm, "work.counter(only)"),
clk("clk"),
reset("reset"),
count("count")
{}
};
Example
Following the example shown above (UM-218), let’s see the generic information that would
be passed to the SystemC foreign module declaration. The generic parameters passed to the
constructor are shown in magenta color:
class counter : public sc_foreign_module {
public:
sc_in<bool> clk;
...
sc_in<bool> clk;
...
#endif
---------------------------------------------------------------------------
// test_ringbuf.h
#ifndef INCLUDED_TEST_RINGBUF
#define INCLUDED_TEST_RINGBUF
#include "ringbuf.h"
SC_MODULE(test_ringbuf)
{
sc_signal<T> iclock;
...
...
SC_CTOR(test_ringbuf)
: iclock("iclock"),
...
...
{
const char* generic_list[9];
generic_list[0] = strdup("int_param=4");
generic_list[1] = strdup("real_param=2.6");
generic_list[2] = strdup("str_param=\"Hello\"");
generic_list[3] = strdup("bool_param=false");
generic_list[4] = strdup("char_param=Y");
generic_list[5] = strdup("bit_param=0");
generic_list[6] = strdup("bv_param=010");
generic_list[7] = strdup("logic_param=Z");
generic_list[8] = strdup("lv_param=01XZ");
};
#endif
---------------------------------------------------------------------------
-- test_ringbuf.cpp
#include "test_ringbuf.h"
SC_MODULE_EXPORT(test_ringbuf);
---------------------------------------------------------------------------
-- ringbuf.vhd
LIBRARY ieee;
USE ieee.std_logic_1164.all;
USE std.textio.all;
ENTITY ringbuf IS
generic (
int_param : integer;
real_param : real;
str_param : string;
bool_param : boolean;
char_param : character;
bit_param : bit;
bv_param : bit_vector(0 to 2);
logic_param : std_logic;
lv_param : std_logic_vector(3 downto 0));
PORT (
clock : IN std_logic;
..
...
);
END ringbuf;
BEGIN
print_param: PROCESS
variable line_out: Line;
BEGIN
write(line_out, string'("int_param="), left);
write(line_out, int_param);
writeline(OUTPUT, line_out);
write(line_out, string'("real_param="), left);
write(line_out, real_param);
writeline(OUTPUT, line_out);
write(line_out, string'("str_param="), left);
write(line_out, str_param);
writeline(OUTPUT, line_out);
write(line_out, string'("bool_param="), left);
write(line_out, bool_param);
writeline(OUTPUT, line_out);
write(line_out, string'("char_param="), left);
write(line_out, char_param);
writeline(OUTPUT, line_out);
write(line_out, string'("bit_param="), left);
write(line_out, bit_param);
writeline(OUTPUT, line_out);
write(line_out, string'("bv_param="), left);
write(line_out, bv_param);
writeline(OUTPUT, line_out);
WAIT FOR 20 NS;
END PROCESS;
END RTL;
Port associations may be named or positional. Use the same port names and port positions
that appear in the SystemC module. Named port associations are case sensitive.
Component declaration
A SystemC design unit can be referenced from a VHDL design as though it is a VHDL
entity. The interface to the design unit can be extracted from the library in the form of a
component declaration by running vgencomp. Given a library and a SystemC module
name, vgencomp writes a component declaration to standard output.
The default component port types are:
• std_logic
• std_logic_vector
Optionally, you can choose:
• bit and bit_vector
Examples
topmod topmod
TOPMOD topmod
TopMod topmod
top_mod top_mod
_topmod \_topmod\
Port clause
A port clause is generated if the module has ports. A corresponding VHDL port is defined
for each named SystemC port.
You can set the VHDL port type to bit or std_logic. If the SystemC port has a range, then
the VHDL port type is bit_vector or std_logic_vector.
Examples
sc_in<sc_logic>p1; p1 : in std_logic;
Configuration declarations are allowed to reference SystemC modules in the entity aspects
of component configurations. However, the configuration declaration cannot extend into a
SystemC instance to configure the instantiations within the SystemC module.
SC_MODULE_EXPORT(transceiver);
sccom -link
The sccom -link command collects the object files created in the work library, and uses
them to build a shared library (.so) in the current work library. If you have changed your
SystemC source code and recompiled it using sccom, then you must run sccom -link before
invoking vsim. Otherwise your changes to the code are not recognized by the simulator.
A ModelSim simulation can be saved to a wave log format (WLF) file for future viewing
or comparison to a current simulation. We use the term "dataset" to refer to a WLF file that
has been reopened for viewing.
You can open more than one WLF file for simultaneous viewing. You can also create
virtual signals that are simple logical combinations of, or logical functions of, signals from
different datasets.
The simulator resolution (see "Simulator resolution limit" (UM-129) or (UM-78)) must be the
same for all datasets you’re comparing, including the current simulation. If you have a
WLF file that is in a different resolution, you can use the wlfman command (CR-416) to
change it.
Important: If you do not use dataset save or dataset snapshot, you must end a
simulation session with a quit or quit -sim command in order to produce a valid WLF
file. If you don’t end the simulation in this manner, the WLF file will not close properly,
and ModelSim may issue the error message "bad magic number" when you try to open
an incomplete dataset in subsequent sessions. If you end up with a "damaged" WLF file,
you can try to "repair" it using the wlfrecover command (CR-420).
Opening datasets
To open a dataset, do one of the following:
• Select File > Open and choose Log Files or use the dataset open command (CR-141).
Click here to
scroll tabs
If you have too many tabs to display in the available space, you can scroll the tabs left or
right by clicking the arrow icons at the bottom right-hand corner of the window.
Design unit type the type (e.g., Module, Entity, etc.) of the design unit
Aside from the four columns listed above, there are numerous other columns related to code
coverage that can be displayed in structure tabs. You can hide or show columns by right-
clicking a column name and selecting the name on the list. See "Workspace pane" (GR-116)
for more details.
GUI
When you have one or more datasets open, you can manage them using the Dataset
Browser. To open the browser, select View > Datasets.
Command line
You can open multiple datasets when the simulator is invoked by specifying more than one
vsim -view <filename> option. By default the dataset prefix will be the filename of the
WLF file. You can specify a different dataset name as an optional qualifier to the
vsim -view switch on the command line using the following syntax:
-view <dataset>=<filename>
view:/top/alu/out
golden:.top.alu.out
Dataset prefixes are not required unless more than one dataset is open, and you want to refer
to something outside the active dataset. When more than one dataset is open, ModelSim
will automatically prefix names in the Wave and List windows with the dataset name. You
can change this default by selecting Tools > Window Preferences (Wave and List
windows).
ModelSim also remembers a "current context" within each open dataset. You can toggle
between the current context of each dataset using the environment command (CR-161),
specifying the dataset without a path. For example:
env foo:
sets the active dataset to foo and the current context to the context last specified for foo.
The context is then applied to any unlocked windows.
The current context of the current dataset (usually referred to as just "current context") is
used for finding objects specified without a path.
The Objects pane can be locked to a specific context of a dataset. Being locked to a dataset
means that the pane will update only when the content of that dataset changes. If locked to
both a dataset and a context (e.g., test: /top/foo), the pane will update only when that
specific context changes. You specify the dataset to which the pane is locked by selecting
File > Environment.
-wlfnocollapse All events for each logged signal are recorded to the WLFCollapseMode = 0
WLF file in the exact order they occur in the
simulation.
When a run completes that includes single stepping or hitting a breakpoint, all events are
flushed to the WLF file regardless of the time collapse mode. It’s possible that single
stepping through part of a simulation may yield a slightly different WLF file than just
running over that piece of code. If particular detail is required in debugging, you should
disable time collapsing.
Virtual signals
Virtual signals are aliases for combinations or subelements of signals written to the WLF
file by the simulation kernel. They can be displayed in the Objects, List, and Wave
windows, accessed by the examine command, and set using the force command. You can
create virtual signals using the Tools > Combine Signals (Wave and List windows)
command or use the virtual signal command (CR-351). Once created, virtual signals can be
dragged and dropped from the Objects pane to the Wave and List windows.
Virtual signals are automatically attached to the design region in the hierarchy that
corresponds to the nearest common ancestor of all the elements of the virtual signal. The
virtual signal command has an -install <region> option to specify where the virtual signal
should be installed. This can be used to install the virtual signal in a user-defined region in
order to reconstruct the original RTL hierarchy when simulating and driving a
post-synthesis, gate-level implementation.
A virtual signal can be used to reconstruct RTL-level design buses that were broken down
during synthesis. The virtual hide command (CR-342) can be used to hide the display of the
broken-down bits if you don't want them cluttering up the Objects pane.
If the virtual signal has elements from more than one WLF file, it will be automatically
installed in the virtual region virtuals:/Signals.
Virtual signals are not hierarchical – if two virtual signals are concatenated to become a
third virtual signal, the resulting virtual signal will be a concatenation of all the scalar
elements of the first two virtual signals.
The definitions of virtuals can be saved to a macro file using the virtual save command
(CR-349). By default, when quitting, ModelSim will append any newly-created virtuals (that
have not been saved) to the virtuals.do file in the local directory.
If you have virtual signals displayed in the Wave or List window when you save the Wave
or List format, you will need to execute the virtuals.do file (or some other equivalent) to
restore the virtual signal definitions before you re-load the Wave or List format during a
later run. There is one exception: "implicit virtuals" are automatically saved with the Wave
or List format.
Virtual functions
Virtual functions behave in the GUI like signals but are not aliases of combinations or
elements of signals logged by the kernel. They consist of logical operations on logged
signals and can be dependent on simulation time. They can be displayed in the Objects,
Wave, and List windows and accessed by the examine command (CR-162), but cannot be
set by the force command (CR-180).
Examples of virtual functions include the following:
• a function defined as the inverse of a given signal
• a function defined as the exclusive-OR of two signals
• a function defined as a repetitive clock
• a function defined as "the rising edge of CLK delayed by 1.34 ns"
Virtual functions can also be used to convert signal types and map signal values.
The result type of a virtual signal can be any of the types supported in the GUI expression
syntax: integer, real, boolean, std_logic, std_logic_vector, and arrays and records of these
types. Verilog types are converted to VHDL 9-state std_logic equivalents and Verilog net
strengths are ignored.
Virtual functions can be created using the virtual function command (CR-339).
Virtual functions are also implicitly created by ModelSim when referencing bit-selects or
part-selects of Verilog registers in the GUI, or when expanding Verilog registers in the
Objects, Wave, or List window. This is necessary because referencing Verilog register
elements requires an intermediate step of shifting and masking of the Verilog "vreg" data
structure.
Virtual regions
User-defined design hierarchy regions can be defined and attached to any existing design
region or to the virtuals context tree. They can be used to reconstruct the RTL hierarchy in
a gate-level design and to locate virtual signals. Thus, virtual signals and virtual regions can
be used in a gate-level design to allow you to use the RTL test bench.
Virtual regions are created and attached using the virtual region command (CR-348).
Virtual types
User-defined enumerated types can be defined in order to display signal bit sequences as
meaningful alphanumeric names. The virtual type is then used in a type conversion
expression to convert a signal to values of the new type. When the converted signal is
displayed in any of the windows, the value will be displayed as the enumeration string
corresponding to the value of the original signal.
Virtual types are created using the virtual type command (CR-354).
9 - Waveform analysis
Chapter contents
Introduction . . . . . . . . . . . . . . . UM-239
Objects you can view . . . . . . . . . . . . UM-239
Wave window overview . . . . . . . . . . . . UM-240
Introduction
When your simulation finishes, you will often want to analyze waveforms to assess and
debug your design. Designers typically use the Wave window for waveform analysis.
However, you can also look at waveform data in a textual format in the List window.
To analyze waveforms in ModelSim, follow these steps:
VHDL objects
(indicated by dark blue diamond in the Wave window)
signals, aliases, process variables, and shared variables
Verilog objects
(indicated by light blue diamond in the Wave window)
nets, registers, variables, and named events
SystemC objects
(indicated by a green diamond in the Wave window)
primitive channels and ports
Virtual objects
(indicated by an orange diamond in the Wave window)
virtual signals, buses, and functions, see; "Virtual Objects (User-defined buses, and more)"
(UM-233) for more information
Comparisons
(indicated by a yellow triangle)
comparison regions and comparison signals; see Waveform Compare (UM-270) for more
information
Assertions
(indicated by a magenta triangle or arrowhead in the Wave window)
PSL assertions
Undock button
Here is an example of a Wave window that is undocked from the MDI frame. All menus
and icons associated with Wave window functions now appear in the menu and toolbar
areas of the Wave window.
Dock button
Undock button
If the Wave window is docked into the Main window MDI frame, all menus and icons that
were in the standalone version of the Wave window move into the Main window menu bar
and toolbar. See "Main window menu bar" (GR-20) for more information.
The Wave window is divided into a number of window panes. All window panes in the
Wave window can be resized by clicking and dragging the bar between any two panes.
Action Method
Add marker Select a line and then select Edit > Add Marker
Delete marker Select a tagged line and then select Edit > Delete Marker
Managing bookmarks
The table below summarizes actions you can take with bookmarks.
Add bookmark Edit > Insert Bookmark bookmark add wave (CR-71)
View bookmark View > Bookmark > <name> bookmark goto wave (CR-73)
Adding bookmarks
To add a bookmark, follow these steps:
1 Zoom the wave window as you see fit using one of the techniques discussed in "Zooming
the Wave window display" (UM-249).
Editing Bookmarks
Once a bookmark exists, you can change its properties by selecting Tools > Bookmarks.
See "Modify Breakpoints dialog" (GR-249) for more details.
The Find dialog gives various options that are discussed further under "Find in .wave
dialog" (GR-233). One option of note is the "Exact" checkbox. Check Exact if you only want
to find objects that match your search exactly. For example, searching for "clk" without
Exact will find /top/clk and clk1.
There are two differences between the Wave and List windows as it relates to the Find
feature:
• In the Wave window you can specify a value to search for in the values pane.
• The find operation works only within the active pane in the Wave window.
The Search dialog gives various options that are discussed further under "Wave Signal
Search dialog" (GR-234). One option of note is Search for Expression. The expression can
involve more than one signal but is limited to signals currently in the window. Expressions
can include constants, variables, and DO files. See "Expression syntax" (CR-23) for more
information.
Note: If your signal values are displayed in binary radix, see "Searching for binary signal
values in the GUI" (CR-29) for details on how signal values are mapped between a binary
radix and std_logic.
The Expression Builder dialog box provides an array of buttons that help you build a GUI
expression. For instance, rather than typing in a signal name, you can select the signal in
the associated Wave or List window and press Insert Selected Signal. All Expression
Builder buttons correspond to the "Expression syntax" (CR-23).
• Put $foo in the Expression: entry box for the Search for Expression selection.
• Issue a searchlog command using foo:
searchlog -expr $foo 0
Operators
Other buttons will add operators of various kinds (see "Expression syntax" (CR-23)), or you
can type them in.
The default radix is symbolic, which means that for an enumerated type, the value pane lists
the actual values of the enumerated type of that object. For the other radixes - binary, octal,
1 Select the signal above which you want to place the divider.
2 If the Wave pane is docked in MDI frame of the Main window, select Add > Divider
from the Main window menu bar. If the Wave window stands alone, undocked from the
Main window, select Insert > Divider from the Wave window menu bar.
3 Specify the divider name in the Wave Divider Properties dialog. The default name is
New Divider. Unnamed dividers are permitted. Simply delete "New Divider" in the
Divider Name field to create an unnamed divider.
4 Specify the divider height (default height is 17 pixels) and then click OK.
You can also insert dividers with the -divider argument to the add wave command (CR-52).
Action Method
In the illustration below, the top split shows the current active simulation with the prefix
"sim," and the bottom split shows a second dataset with the prefix "gold".
The default radix is symbolic, which means that for an enumerated type, the window lists
the actual values of the enumerated type of that object. For the other radixes - binary, octal,
decimal, unsigned, hexadecimal, or ASCII - the object value is converted to an appropriate
representation in that radix.
Changing the radix can make it easier to view information in the List window. Compare
the image below (with decimal values) with the image on page UM-243 (with symbolic
values).
Aside from the List Signal Properties dialog, there are three other ways to change the radix:
• Change the default radix for the current simulation using Simulate > Runtime Options
(Main window)
• Change the default radix for the current simulation using the radix command (CR-241).
• Change the default radix permanently by editing the DefaultRadix (UM-531) variable in
the modelsim.ini file.
2 Edit and format the objects to create the view you want.
3 Save the format to a file by selecting File > Save > Format.
To use the format file, start with a blank Wave or List window and run the DO file in one
of two ways:
• Invoke the do command (CR-151) from the command line:
VSIM> do <my_format_file>
• Select File > Open > Format.
Note: Window format files are design-specific. Use them only with the design you were
simulating when they were created.
• Events
writes a text file containing transitions during simulation
@0 +0
/a X
/b X
/cin U
/sum X
/cout U
@0 +1
/a 0
/b 1
/cin 0
• TSSI
writes a file in standard TSSI format; see also, the write tssi command (CR-429)
0 00000000000000010?????????
2 00000000000000010???????1?
3 00000000000000010??????010
4 00000000000000010000000010
100 00000001000000010000000010
You can also save List window output using the write list command (CR-424).
Example
In the illustration below, three signals have been combined to form a new bus called "bus".
Note that the component signals are listed in the order in which they were selected in the
Wave window. Also note that the value of the bus is made up of the values of its component
signals, arranged in a specific order.
The dialog gives various options that are discussed further under "Modify Display
Properties dialog" (GR-162). The following table summaries the options:
Option Description
Option Description
Strobe trigger Specify an interval at which you want to trigger data display
2 Check the Use Gating Expression check box and click Use Expression Builder.
3 Select the signal in the List window that you want to be the enable signal by clicking on
its name in the header area of the List window.
4 Click Insert Selected Signal and then 'rising in the Expression Builder.
When you run the simulation, List window entries for clk, a, b, and c appear only when clk
changes.
If you want to display on rising edges only, you have two options:
1 Turn off the List window triggering on the clock signal, and then define a repeating
strobe for the List window.
2 Define a "gating expression" for the List window that requires the clock to be in a
specified state. See above.
Miscellaneous tasks
Examining waveform values
You can use your mouse to display a dialog that shows the value of a waveform at a
particular time. You can do this two ways:
• Rest your mouse pointer on a waveform. After a short delay, a dialog will pop-up that
displays the value for the time at which your mouse pointer is positioned. If you’d prefer
that this popup not display, it can be toggled off in the display properties. See "Setting
Wave window display properties" (UM-255).
• Right-click a waveform and select Examine. A dialog displays the value for the time at
which you clicked your mouse. This method works in the List window as well.
Waveform Compare
The ModelSim Waveform Compare feature allows you to compare simulation runs.
Differences encountered in the comparison are summarized and listed in the Main window
transcript. Differences are also shown in the Wave and List windows, and you can write a
list of the differences to a file using the compare info command (CR-106).
1 Run one simulation and save the dataset. For more information on saving datasets, see
"Saving a simulation to a WLF file" (UM-227).
The number of elements must match for vectors; specific indexes are ignored.
Comparison Wizard
The simplest method for setting up a comparison is using the Wizard. The wizard is a series
of dialogs that walks you through the process. To start the Wizard, select Tools >
Waveform Compare > Comparison Wizard from either the Wave or Main window.
The graphic below shows the first dialog in the Wizard. As you can see from this example,
the dialogs include instructions on the left-hand side.
Comparison commands
There are numerous commands that give you complete control over a comparison. These
commands can be entered in the Main window transcript or run via a DO file. The
commands are detailed in the ModelSim Command Reference, but the following example
shows the basic sequence:
compare start gold.wlf vsim.wlf
compare add /*
compare run
1 Initiate the comparison by specifying the reference and test datasets. See "Starting a
waveform comparison" (UM-272) for details.
2 Add objects to the comparison. See "Adding signals, regions, and clocks" (UM-274) for
details.
3 Specify the comparison method. See "Specifying the comparison method" (UM-276) for
details.
4 Configure comparison options. See "Setting compare options" (UM-278) for details.
5 Run the comparison by selecting Tools > Waveform Compare > Run Comparison.
6 View the results. See "Viewing differences in the Wave window" (UM-279), "Viewing
differences in the List window" (UM-281), and "Viewing differences in textual format"
(UM-282)for details.
Waveform Compare is initiated from either the Main or Wave window by selecting Tools
>Waveform Compare > Start Comparison.
Reference Dataset
The Reference Dataset is the .wlf file to which the test dataset will be compared. It can be
a saved dataset, the current simulation dataset, or any part of the current simulation dataset.
Test Dataset
The Test Dataset is the .wlf file that will be compared against the Reference Dataset. Like
the Reference Dataset, it can be a saved dataset, the current simulation dataset, or any part
of the current simulation dataset.
Once you click OK in the Start Comparison dialog box, ModelSim adds a Compare tab to
the Main window.
After adding the signals, regions, and/or clocks you want to use in the comparison (see
"Adding signals, regions, and clocks" (UM-274)), you will be able to drag compare objects
from this tab into the Wave and List windows.
Adding signals
Clicking Tools > Waveform Compare > Add > Compare by Signal in the Wave window
opens the structure_browser window, where you can specify signals to be used in the
comparison.
Adding regions
Rather than comparing individual signals, you can also compare entire regions of your
design. Select Tools > Waveform Compare > Add > Compare by Region to open the
Add Comparison by Region dialog. The dialog has several options which are detailed in the
GUI reference appendix.
Adding clocks
You add clocks when you want to perform a clocked comparison. See "Specifying the
comparison method" (UM-276) for details.
Continuous comparison
Continuous comparisons are the default. You have the option of specifying leading and
trailing tolerances and a when expression that must evaluate to "true" or 1 at the signal edge
for the comparison to become effective. See "Add Signal Options dialog" (GR-244) for more
details on this dialog.
Clocked comparison
To specify a clocked comparison you must define a clock in the Add Clock dialog. You can
access this dialog via the Clocks button in the Comparison Method tab or by selecting
Tools > Waveform Compare > Add > Clocks.
Options in this dialog include setting the maximum number of differences allowed before
the comparison terminates, specifying signal value matching rules, and saving or resetting
the defaults. See "Comparison Options dialog" (GR-247) for more details.
If you compare two signals from different regions, the signal names include the uncommon
part of the path.
In comparisons of signals with multiple bits, you can display them in "buswise" or
"bitwise" format. Buswise format lists the busses under the compare object whereas bitwise
format lists each individual bit under the compare object. To select one format or the other,
click your right mouse button on the plus sign (’+’) next to a compare object.
Timing differences are also indicated by red bars in the vertical and horizontal scroll bars
of the waveform display, and by red difference markers on the waveforms themselves.
Rectangular difference markers denote continuous differences. Diamond difference
markers denote clocked differences. Placing your mouse cursor over any difference marker
will initiate a popup display that provides timing details for that difference. You can toggle
this popup on and off in the "Window Preferences dialog" (GR-255).
The values column of the Wave window displays the words "match" or "diff" for every test
signal, depending on the location of the selected cursor. "Match" indicates that the value of
the test signal matches the value of the reference signal at the time of the selected cursor.
"Diff" indicates a difference between the test and reference signal values at the selected
cursor.
Annotating differences
You can tag differences with textual notes that are included in the difference details popup
and comparison reports. Click a difference with the right mouse button, and select
Annotate Diff. Or, use the compare annotate (CR-98) command.
Compare icons
The Wave window includes six comparison icons that
let you quickly jump between differences. From left to
right, the icons do the following: find first difference,
find previous annotated difference, find previous difference, find next difference, find next
annotated difference, find last difference. Use these icons to move the selected cursor.
These buttons cycle through differences on all signals. To view differences for just the
selected signal, press <tab> and <shift - tab> on your keyboard.
Note: If you have differences on individual bits of a bus, the compare icons will stop on
those differences but <tab> and <shift - tab> will not.
The compare icons cycle through comparison objects in all open Wave windows. If you
have two Wave windows displayed, each containing different comparison objects, the
compare icons will cycle through the differences displayed in both windows.
Introduction
The ModelSim Waveform Editor offers a simple method for creating design stimulus. You
can generate and edit waveforms in a graphical manner and then drive the simulation with
those waveforms. With Waveform Editor you can do the following:
• Create waveforms using four predefined patterns: clock, random, repeater, and counter.
See "Creating waveforms from patterns" (GR-289).
• Edit waveforms with numerous functions including inserting, deleting, and stretching
edges; mirroring, inverting, and copying waveform sections; and changing waveform
values on-the-fly. See "Editing waveforms" (GR-290).
• Drive the simulation directly from the created waveforms
• Save created waveforms to four stimulus file formats: Tcl force format, extended VCD
format, Verilog module, or VHDL architecture. The HDL formats include code that
matches the created waveforms and can be used in testbenches to drive a simulation. See
"Exporting waveforms to a stimulus file" (GR-294)
Limitations
The current version does not support the following:
• Enumerated signals, records, multi-dimensional arrays, and memories
• User-defined types
• SystemC or SystemVerilog
Getting started
You can use Waveform Editor before or after loading a design. Regardless of which
method you choose, you will select design objects and use them as the basis for created
waveforms.
1 Right-click a design unit on the Library tab of the Workspace pane and select Create
Wave.
2 Edit the waveforms in the Wave window. See "Editing waveforms" (GR-290) for more
details.
3 Run the simulation (see "Simulating directly from waveform editor" (GR-293)) or save
the created waveforms to a stimulus file (see "Exporting waveforms to a stimulus file"
(GR-294)).
1 Right-click a block in the structure tab of the Workspace pane or an object in the Object
pane and select Create Wave.
2 Use the Create Pattern wizard to create the waveforms (see "Creating waveforms from
patterns" (GR-289)).
4 Run the simulation (see "Simulating directly from waveform editor" (GR-293)) or save
the created waveforms to a stimulus file (see "Exporting waveforms to a stimulus file"
(GR-294)).
In this dialog you specify the signal that the waveform will be based upon, the Drive Type
(if applicable), the start and end time for the waveform, and the pattern for the waveform.
The second dialog in the wizard lets you specify the appropriate attributes based on the
pattern you select. The table below shows the five available patterns and their attributes:
Pattern Description
Clock Specify an initial value, duty cycle, and clock period for the waveform.
Random Generates different patterns depending upon the seed value. Specify
the type (normal or uniform), an initial value, and a seed value. If you
don’t specify a seed value, ModelSim uses a default value of 5.
Repeater Specify an initial value and pattern that repeats. You can also specify
how many times the pattern repeats.
Counter Specify start and end values, time period, type (Range, Binary, Gray,
One Hot, Zero Hot, Johnson), counter direction, step count, and repeat
number.
Editing waveforms
You can edit waveforms interactively with menu commands, mouse actions, or by using
the wave edit command (CR-400).
To edit waveforms in the Wave window, follow these steps:
1 Create an editable pattern as described under "Creating waveforms from patterns" (GR-
289).
2 Enter editing mode by selecting View > Mouse Mode > Edit Mode or by
clicking the Edit Mode icon.
3 Select an edge or a section of the waveform with your mouse. See "Selecting
parts of the waveform" (GR-291) for more details.
4 Select a command from the Edit > Edit Wave menu or right-click on the waveform and
select a command from the Edit Wave context menu.
The table below summarizes the editing commands that are available.
Operation Description
Paste Paste the contents of the clipboard over the selected section or at the
active cursor location
Stretch Edge Move an edge forward/backward by "stretching" the waveform; see
"Stretching and moving edges" (GR-292) for more information
Move Edge Move an edge forward/backward without changing other edges; see
"Stretching and moving edges" (GR-292) for more information
Drive Type Change the drive type of the selected portion of the waveform
Extend All Waves Extend all created waveforms by the specified amount or to the
specified simulation time; ModelSim cannot undo this edit or any
edits done prior to an extend command
Undo Undo waveform edits (except changing drive type and extending all
waves)
These commands can also be accessed via toolbar buttons. See "Waveform editor toolbar"
(GR-222)for more information.
Action Method
Select a waveform edge Click on or just to the right of the waveform edge
Select a section of multiple waveforms Click-and-drag the mouse pointer while holding
the <Shift> key
Stretch an edge Hold the <Ctrl> key and drag the edge
Move an edge Hold the <Ctrl> key and drag the edge with the
2nd (middle) mouse button
Here are some points to keep in mind about stretching and moving edges:
• If you stretch an edge forward, more waveform is inserted at the beginning of simulation
time.
• If you stretch an edge backward, waveform is deleted at the beginning of simulation time.
• If you move an edge past another edge, either forward or backward, the edge you moved
past is deleted.
Format Description
Force format Creates a Tcl script that contains force commands necessary to
recreate the waveforms; source the file when loading the
simulation as described under "Driving simulation with the
saved stimulus file" (GR-295)
EVCD format Creates an extended VCD file which can be reloaded using the
Import > EVCD File command or can be used with the
-vcdstim argument to vsim (CR-373) to simulate the design
VHDL Testbench Creates a VHDL architecture that you load as the top-level
design unit
Verilog Testbench Creates a Verilog module that you load as the top-level design
unit
a.You can also use the Import > EVCD command from the Wave window. See below
for more details on working with EVCD files.
Select a signal from the drop-down arrow and click OK. You will repeat this process for
each signal you selected.
This chapter discusses how to use the Dataflow window for tracing signal values and
browsing the physical connectivity of your design.
Note: ModelSim versions operating without a dataflow license feature have limited
Dataflow functionality. Without the license feature, the window will show only one
process and its attached signals or one signal and its attached processes. Contact your
Mentor Graphics sales representative if you currently don’t have a dataflow feature.
Window Link
Main window (GR-14) select a signal or process in the Dataflow window, and
the structure tab updates if that object is in a different
design unit
Active Processes pane (GR-108) select a process in either window, and that process is
highlighted in the other
Objects pane (GR-184) select a design object in either window, and that object
is highlighted in the other
Source window (GR-199) select an object in the Dataflow window, and the
Source window updates if that object is in a
different source file
Expand net to all drivers and readers Navigate > Expand net
display driver(s) and reader(s) of the selected
signal, net, or register
As you expand the view, note that the "layout" of the design may adjust to best show the
connectivity. For example, the location of an input signal may shift from the bottom to the
top of a process.
You can clear this highlighting using the Edit > Erase highlight command.
The wave viewer is opened using the View > Show Wave command.
One common scenario is to place signals in the wave viewer and the Dataflow panes, run
the design for some amount of time, and then use time cursors to investigate value changes.
In other words, as you place and move cursors in the wave viewer pane (see "Measuring
time with cursors in the Wave window" (UM-245) for details), the signal values update in the
Dataflow pane.
Another scenario is to select a process in the Dataflow pane, which automatically adds to
the wave viewer pane all signals attached to the process.
See "Tracing events (causality)" (UM-306) for another example of using the embedded wave
viewer.
Zoom Full
zoom out to view
the entire
schematic
1 Log all signals before starting the simulation (add log -r /*).
2 After running a simulation for some period of time, open the Dataflow window and the
wave viewer pane.
3 Add a process or signal of interest into the Dataflow window (if adding a signal, find its
driving process). Select the process and all signals attached to the selected process will
appear in the wave viewer pane.
4 Place a time cursor on an edge of interest; the edge should be on a signal that is an output
of the process.
6 Keep selecting Trace > Trace next event until you've reached an input event of interest.
Note that the signals with the events are selected in the wave pane.
The Dataflow display "jumps" to the source of the selected input event(s). The operation
follows all signals selected in the wave viewer pane. You can change which signals are
followed by changing the selection.
2 Log all signals in the design or any signals that may possibly contribute to the unknown
value (log -r /* will log all signals in the design).
3 Add signals to the Wave window or wave viewer pane, and run your design the desired
length of time.
5 Add the signal of interest to the Dataflow window, making sure the signal is selected.
6 Select Trace > TraceX, Trace > TraceX Delay, Trace > ChaseX, or Trace > ChaseX
Delay.
Symbol mapping
The Dataflow window has built-in mappings for all Verilog primitive gates (i.e., AND, OR,
etc.). For components other than Verilog primitives, you can define a mapping between
processes and built-in symbols. This is done through a file containing name pairs, one per
line, where the first name is the concatenation of the design unit and process names,
(DUname.Processname), and the second name is the name of a built-in symbol. For
example:
xorg(only).p1 XOR
org(only).p1 OR
andg(only).p1 AND
User-defined symbols
You can also define your own symbols using an ASCII symbol library file format for
defining symbol shapes. This capability is delivered via Concept Engineering’s NlviewTM
widget Symlib format. For more specific details on this widget, see www.model.com/
support/documentation/BOOK/nlviewSymlib.pdf.
The Dataflow window will search the current working directory, and inside each library
referenced by the design, for the file dataflow.sym. Any and all files found will be given to
the Nlview widget to use for symbol lookups. Again, as with the built-in symbols, the DU
name and optional process name is used for the symbol lookup. Here's an example of a
symbol for a full adder:
symbol adder(structural) * DEF \
port a in -loc -12 -15 0 -15 \
pinattrdsp @name -cl 2 -15 8 \
port b in -loc -12 15 0 15 \
pinattrdsp @name -cl 2 15 8 \
port cin in -loc 20 -40 20 -28 \
pinattrdsp @name -uc 19 -26 8 \
port cout out -loc 20 40 20 28 \
pinattrdsp @name -lc 19 26 8 \
port sum out -loc 63 0 51 0 \
pinattrdsp @name -cr 49 0 8 \
path 10 0 0 7 \
path 0 7 0 35 \
path 0 35 51 17 \
path 51 17 51 -17 \
path 51 -17 0 -35 \
path 0 -35 0 -7 \
path 0 -7 10 0
Port mapping is done by name for these symbols, so the port names in the symbol definition
must match the port names of the Entity|Module|Process (in the case of the process, it’s the
signal names that the process reads/writes).
Important: When you create or modify a symlib file, you must generate a file index.
This index is how the Nlview widget finds and extracts symbols from the file. To
generate the index, select Tools > Create symlib index (Dataflow window) and specify
the symlib file. The file will be rewritten with a correct, up-to-date index.
The ModelSim profiler combines a statistical sampling profiler with a memory allocation
profiler to provide instance specific execution and memory allocation data. It allows you to
quickly determine how your memory is being allocated and easily identify areas in your
simulation where performance can be improved. The profiler can be used at all levels of
design simulation – Functional, RTL, and Gate Level – and has the potential to save hours
of regression test time. In addition, ASIC and FPGA design flows benefit from the use of
this tool.
Note: The functionality described in this chapter requires a profiler license feature in
your ModelSim license file. Please contact your Mentor Graphics sales representative if
you currently do not have such a feature.
Platform information
Getting started
Memory allocation profiling and statistical sampling are enabled separately.
You can use the graphic user interface as follows to perform the same task.
1 Select Simulate > Start Simulation or the Simulate icon, to open the Start Simulation
dialog box.
If memory allocation during elaboration is not a concern, the memory allocation profiler
can be enabled at any time after the design is loaded by doing any one of the following:
• select Tools > Profile > Memory
• use the -m argument with the profile on command (CR-228)
profile on -m
• click the Memory Profiling icon
These switches add symbols to the .dll file that the profiler can use in its report.
In the Call Tree and Structural views, you can expand and collapse the various levels to
hide data that is not useful to the current analysis and/or is cluttering the display. Click on
the '+' box next to an object name to expand the hierarchy and show supporting functions
and/or instances beneath it. Click the '-' box to collapse all levels beneath the entry.
You can also right click any function or instance in the Call Tree and Structural views to
obtain popup menu selections for rooting the display to the currently selected item, to
ascend the displayed root one level, or to expand and collapse the hierarchy. See Profiler
popup menu commands (GR-195).
View Source
When View Source is selected the Source window opens to the location of the selected
function in the source code.
Function Usage
When Function Usage is selected, the Profile Details pane opens and displays all instances
using the selected function. In the Profile Details pane shown below, all the instances using
function Tcl_Close are displayed. The statistical performance and memory allocation data
shows how much simulation time and memory is used by Tcl_Close in each instance.
Instance Usage
When Instance Usage is selected all instances with the same definition as the selected
instance will be displayed in the Profile Details pane.
View Instantiation
When View Instantiation is selected the Source window opens to the point in the source
code where the selected instance is instantiated.
Display in Structural
When Display in Structural is selected the Structural view of the Profile window expands
to display all occurrences of the selected function and puts the selected function into a
search buffer so you can easily cycle across all occurrences of that function.
You can perform the same task by right-clicking any function or instance in any one of the
three Profile views and selecting View Source from the popup menu that opens.
When you right-click an instance in the Structural profile view, the View Instantiation
selection will become active in the popup menu. Selecting this option opens the
instantiation in a Source window and highlights it.
The right-click popup menu also allows you to change the root instance of the display,
ascend to the next highest root instance, or reset the root instance to the top level instance.
The selection of a context in the structure tab of the Workspace pane will cause the root
display to be set in the Structural view.
will produce a Call Tree profile report in a text file called calltree.rpt, as shown here.
See the profile report command (CR-231) in the Command Reference for complete details
on profiler reporting options.
Select Tools > Profile > Profile Report to open the Profile Report dialog. From the dialog
below, a Structural profile report will be created from the root instance pathname, /test_sm/
sm_seq0. The report will include function call hierarchy and three structure levels. Both
performance and memory data will be displayed with a cutoff of 3% - meaning, the report
will not contain any functions or instances that do not use 3% or more of simulation time
or memory. The report will be written to a file called profile.out and, since the "View file"
box is selected, it will be generated and displayed in Notepad when the OK button is
clicked.
Note: The functionality described in this chapter requires a coverage license feature in
your ModelSim license file. Please contact your Mentor Graphics sales representative if
you currently do not have such a feature.
Introduction
ModelSim code coverage gives you graphical and report file feedback on which statements,
branches, conditions, and expressions in your source code have been executed. It also
measures bits of logic that have been toggled during execution.
With coverage enabled, ModelSim counts how many times each executable statement,
branch, condition, expression, and logic node in each instance is executed during
simulation. Statement coverage counts the execution of each statement on a line
individually, even if there are multiple statements in a line. Branch coverage counts the
execution of each conditional "if/then/else" and "case" statement and indicates when a true
or false condition has not executed. Condition coverage analyzes the decision made in "if"
and ternary statements and is an extension to branch coverage. Expression coverage
analyzes the expressions on the right hand side of assignment statements, and is similar to
condition coverage. Toggle coverage counts each time a logic node transitions from one
state to another.
Coverage statistics are displayed in the Main, Objects, and Source windows and also can
be output in different text reports (see "Reporting coverage data" (UM-350)). Raw coverage
data can be saved and recalled, or merged with coverage data from the current simulation
(see "Saving and reloading coverage data" (UM-354)).
ModelSim code coverage offers these benefits:
• It is totally non-intrusive because it’s integrated into the ModelSim engine – it doesn’t
require instrumented HDL code as do third-party coverage products.
• It has very little impact on simulation performance (typically 5 to 10 percent).
• It allows you to merge sets of coverage data without requiring elaboration of the design
or a simulation license.
1 Compile the design using the -cover bcest argument to vcom (CR-311) or vlog (CR-358).
Supported types
ModelSim code coverage supports only certain data types.
VHDL
Supported types are scalar std_ulogic/std_logic. The tool doesn’t currently support bit or
boolean.
Vector and integer and real are not supported directly. However, subexpressions that
involve an unsupported type and a relational operator and produce a boolean result are
supported. These types of subexpressions are treated as an external expression that is first
evaluated and then used as a boolean input to the full condition. The subexpression can look
like:
(var <relop> const)
or
(var1 <relop> var2)
where "var," "var1," and "var2" may be of any type; "<relop>" is a relational operator (e.g.,
<, >, >=); and "const" is a constant of the appropriate type.
Verilog
Supported types are net and one-bit register, but subexpressions of the form:
(var1 <relop> var2)
are supported, where the variables may be multiple-bit registers or integer or real.
SystemC
Code coverage does not work on SystemC design units.
• Package bodies are not instance-specific: ModelSim sums the counts for all invocations
no matter who the caller is. Also, all standard and accelerated packages are ignored for
coverage statistics calculation.
• Design units compiled with -nodebug are ignored, as if they were excluded.
1 Use the -cover argument to vcom or vlog when you compile your design. This argument
tells ModelSim which coverage statistics to collect. For example:
vlog top.v proc.v cache.v -cover bcesx
Each character after the -cover argument identifies a type of coverage statistic: "b"
indicates branch, "c" indicates condition, "e" indicates expression, "s" indicates
statement, "t" indicates 2-transition toggle, and "x" indicates extended 6-transition toggle
coverage (t and x are mutually exclusive). See "Enabling Toggle coverage" (UM-343) for
details on two other methods for enabling toggle coverage.
2 Use the -coverage argument to vsim when you simulate your design. For example:
vsim -coverage work.top
In ModelSim versions prior to 5.8, you didn’t have to enable coverage at compile time.
Code coverage metrics (statement and branch coverage) were turned on just by using the
-coverage argument to vsim. For backwards compatibility, ModelSim will still display
statement statistics if you simulate with coverage enabled, even if you don’t use the -cover
argument when you compile the design.
To enable coverage from the graphic interface, first select Compile > Compile Options
and select the Coverage tab. Alternatively, if you are using a project, right-click on a
selected design object (or objects) and select Properties.
Next, select Simulate > Start Simulation and check Enable code coverage on the Others
tab.
Workspace
Current Instance
Missed Coverage Exclusions Coverage Details
The table below summarizes the Main window coverage panes. For further details, see
"Code coverage panes" (GR-116).
Workspace displays coverage data and graphs for each design object or file
Missed Coverage displays missed coverage for the selected design object or file
Current exclusionsa lists all files and lines that are excluded from the current analysis
Instance coverage displays coverage statistics for each instance in a flat format
a.The Current Exclusions pane does not display by default. Select View > Code Cov-
erage > Current Exclusions to display the pane.
When you hover the cursor over a line of code (see line 58 in the illustration above), the
number of statement and branch executions, or "hits," will be displayed in place of the
check marks and Xs. If you prefer, you can display only numbers by selecting Tools >
Code Coverage > Show Coverage Numbers.
Also, when you click in either the Hits or BC column, the Details pane in the Main window
updates to display information on that line.
You can skip to "missed lines" three ways: select Edit > Previous Coverage Miss and Edit
> Next Coverage Miss from the menu bar; click the Previous zero hits and Next zero hits
icons on the toolbar; or press <Shift> - <Tab> (previous miss) or Tab (next miss).
Toggle coverage
Toggle coverage is the ability to count and collect changes of state on specified nodes,
including Verilog nets and registers and the following VHDL signal types: bit, bit_vector,
std_logic, and std_logic_vector. Toggle coverage is integrated as a metric into the coverage
tool so that the use model and reporting are the same as the other coverage metrics.
There are two modes of toggle coverage operation - standard and extended. Standard toggle
coverage only counts Low or 0 <--> High or 1 transitions. Extended toggle coverage counts
these transitions plus the following:
Z --> 1 or H
Z --> 0 or L
1 or H --> Z
0 or L --> Z
This extended coverage allows a more detailed view of testbench effectiveness and is
especially useful for examining coverage of tri-state signals. It helps to ensure, for example,
that a bus has toggled from high 'Z' to a '1' or '0', and a '1' or '0' back to a high 'Z'.
Toggle coverage will ignore zero-delay glitches.
2 using the Tools > Toggle Coverage > Add or Tools > Toggle Coverage > Extended
selections in the Main window menu.
1 Enable toggle statistics collection for all signals using the -cover t/x argument to vcom
or vlog.
2 Exclude certain signals by disabling them with the toggle disable command.
The toggle enable command (CR-282) re-enables toggle statistics collection on nodes
whose toggle coverage has previously been disabled via the toggle disable command. (See
the Command Reference for correct syntax.)
You can produce this same information using the coverage report command (CR-132).
Note: If you want to ensure that you are reporting all signals in the design, use the
-nocollapse argument to vsim when you load your design. Without this argument, the
simulator collapses certain ports that are connected to the same signal in order to improve
performance, and those collapsed signals will not appear in the report. The -nocollapse
argument degrades simulator performance, so it should be used only when it is absolutely
necessary to see all signals in a toggle report.
See "Filter instance list dialog" (GR-92) for details on this dialog.
Bracket the line or lines you want to exclude with these pragmas.
Here are some points to keep in mind about using these pragmas:
• Pragmas are enforced at the design unit level only. For example, if you put "-- coverage
off" before an architecture declaration, all statements in that architecture will be excluded
from coverage; however, statements in all following design units will be included in
statement coverage (until the next "--coverage off").
• Pragmas cannot be used to exclude specific conditions or expressions within lines.
Syntax
<filename>...
[[<range> ...] [<line#> ...]] | all
or
Arguments
<filename>
The name of the file you want to exclude. Required if you are not specifying an instance.
The filter file may include an unlimited number of filename entries, each on its own line.
You may use environment variables in the pathname.
begin instance <instance_name>
The name of an instance for which you want to exclude lines. Required if you don’t
specify <filename>. The filter file may include an unlimited number of instances.
<inst_filename>
The name of the file(s) that compose the instance from which you are excluding lines.
Optional.
<range> ...
A range of line numbers you want to exclude. Optional. Enter the range in "# - #" format.
For example, 32 - 35. You can specify multiple ranges separated by spaces.
<line#> ...
A line number that you want to exclude. Optional. You can specify multiple line numbers
separated by spaces.
all
When used with <filename>, specifies that all lines in the file should be excluded. When
used with <instance_name>, specifies that all lines in the instance and all instances
contained within the specified instance should be excluded. Required if a range or line
number is not specified.
Example
control.vhd
72 - 76 84 93
testring.vhd
all
begin instance /test_delta/chip/bid01_inst
src/delta/buffers.vhd
45-46
end instance
Excluding condition and expression udp truth table lines and rows
You can also use exclusion filter files to exclude condition and expression udp truth table
rows.
Syntax
-c | -e {<ln> <rn|rn1-rn2>...}
Arguments
-c | -e
Determines whether to exclude condition (-c) or expression (-e) udp truth table rows.
<ln> ...
The line number containing the condition or expression. The line number and list of row
numbers are surrounded by curly braces.
<rn | rn1 - rn2>
A space separated list of row numbers or ranges of row numbers referring to the udp truth
table rows that you want excluded.
XML output
You can output coverage reports in XML format by checking Write XML Format in the
Coverage Report dialog. The following example is an abbreviated "By Instance" report that
includes line details:
<?xml version="1.0"?>
<report xmlns="http://model.com/coverage"
lines="1"
byInstance="1">
<instance path="/test_delta/chip/control_126k_inst" du="mode_two_control">
<source_table files="1">
<file fn="0" path="C:/modelsim_examples/coverage/Modetwo.v"></file>
</source_table>
<statements active="30" hits="17" percent="56.7"> </statements>
<statement_data>
<stmt fn="0" ln="39" st="1" hits="82"> </stmt>
<stmt fn="0" ln="42" st="1" hits="82"> </stmt>
<stmt fn="0" ln="44" st="1" hits="82"> </stmt>
"fn" stands for filename, "ln" stands for line number, and "st" stands for statement.
There is also an XSL stylesheet named covreport.xsl located in <install_dir>/modeltech/
examples. Use it as a foundation for building your own customized report translators.
Sample reports
Below are two abbreviated coverage reports with descriptions of select fields.
The "%" field shows the percentage of statements in the file that had zero coverage.
The "Stmt" field identifies the number of statements with zero coverage on that line.
Value Meaning
- the field is irrelevant to that particular line of code; for example, line
665 in the report above will never have an entry under the True column
See "Load Coverage Data dialog" (GR-89) for details on this dialog.
Condition coverage
Condition coverage analyzes the decision made in "if" and ternary statements and is an
extension to branch coverage. A truth table is constructed for the condition expression and
counts are kept for each row of the truth table that occurs. For example, the following IF
statement:
Line 180: IF (a or b) THEN x := 0; else x := 1; endif;
counts a |b ||(a or b)
Row 1 5 1 - 1
Row 2 0 - 1 1
Row 3 8 0 0 0
unknown 0
Row 1 indicates that (a or b) is true if a is true, no matter what b is. The "counts" column
indicates that this combination has executed 5 times. The '-' character means "don't care."
Likewise, row 2 indicates that the result is true if b is true no matter what a is, and this
combination has executed zero times. Finally, row 3 indicates that the result is always zero
when a is zero and b is zero, and that this combination has executed 8 times.
The truth table body only deals with boolean values. If any inputs are unknown, the result
is set to unknown and is counted.
Values that are vectors are treated as subexpressions external to the table until they resolve
to a boolean result. For example, take the IF statement:
Line 38:IF ((e = '1') AND (bus = "0111")) ...
A truth table will be generated in which bus = "0111" is evaluated as a subexpression and
the result, which is boolean, becomes an input to the truth table. The truth table looks as
follows:
Row 1 0 0 - 0
Row 2 10 - 0 0
Row 3 1 1 1 1
unknown 0 0
Index expressions also serve as inputs to the table. Conditions containing function calls
cannot be handled and will be ignored for condition coverage.
If a line contains a condition that is uncovered - some part of its truth table was not
encountered - that line will appear in the Missed Coverage pane under the Conditions tab.
When that line is selected, the condition truth table will appear in the Details pane and the
line will be highlighted in the Source window.
Condition coverage truth tables are printed in coverage reports when the Condition
Coverage type is selected in the Coverage Reports dialog (see "Reporting coverage data"
(UM-350)) or when the -lines argument is specified in the coverage report command and
one or more of the rows has a zero hit count.
Expression coverage
Expression coverage analyzes the expressions on the right hand side of assignment
statements and counts when these expressions are executed. For expressions that involve
boolean operators, a truth table is constructed and counts are tabulated for conditions
matching rows in the truth table.
For example, take the statement:
Line 236: x <= a xor (not b(0));
This statement results in the following truth table, with associated counts.
Row 1 1 0 0 1 1
Row 2 0 0 1 0 0
Row 3 2 1 0 0 1
Row 4 0 1 1 1 0
unknown 0
If a line contains an expression that is uncovered - some part of its truth table was not
encountered - that line will appear in the Missed Coverage pane under the Expressions tab.
When that line is selected, the expression truth table will appear in the Details pane and the
line will be highlighted in the Source window.
As with condition coverage, expression coverage truth tables are printed in coverage
reports when the Expression Coverage type is selected in the Coverage Reports dialog (see
"Reporting coverage data" (UM-350)) or when the -lines argument is specified in the
coverage report command and one or more of the rows has a zero hit count.
14 - PSL Assertions
Chapter contents
What are assertions? . . . . . . . . . . . . . UM-360
Definition . . . . . . . . . . . . . . . UM-360
Types of assertions . . . . . . . . . . . . UM-360
PSL assertion language . . . . . . . . . . . UM-361
Definition
An assertion is a design property that is evaluated by a tool. A property is a statement about
a design that evaluates to true or false. Properties tell a tool what the design should do, what
it should not do, or what limits exist on its behavior. In effect we are saying, assert that this
property is true; if it is false, tell me.
Types of assertions
Broadly speaking there are three types of assertions: interface/system level assertions,
internal architecture assertions, and functional coverage assessment.
Interface/system-level assertions
Sometimes referred to as "black-box," these types of assertions are high-level properties of
a design that describe only the inputs of a module or system. The interfaces are generally
between major blocks of a design that are owned by different designers. The assertions are
typically placed in an external file and then attached to a design unit.
Verification engineers typically apply this use model. Many organizations prohibit the
verification team from touching synthesizable RTL code. Therefore, they cannot embed
assertions. Also, assertions that are defined in a separate file are easier to reuse at multiple
abstraction levels (architectural, RTL and gate) as the design objects that they reference are
very likely to exist at all levels.
HDL with
embedded assertions or HDL assertions file
vsim
Wave Assertions
window pane
ModelSim lets you embed assertions within your Verilog or VHDL code or supply them in
a separate file. If the assertions are embedded, vlog/vcom will compile them automatically.
If the assertions are in a separate file, you add the -pslfile argument to vlog/vcom. Once
compilation is complete, you invoke the simulator vsim on the design. The simulator
automatically handles any assertions that are present in the design. From there you run the
simulation and debug any assertion failures.
Limitations
The current release has some limitations. Most of these features will be added in future
releases.
• Only the simple subset of PSL is supported.
• Vunits cannot be bound to a design unit instance. They can be bound only to a module,
entity, and architecture.
• There is no support for verification unit inheritance–vunits cannot be derived from other
vunits.
• There is no support for unclocked assertions. Level-sensitive clock expressions are not
allowed.
• There is no support for %for and %if preprocessor commands.
• There is no support for integer, structures, and union in the modeling layer. The only PSL
built-in functions currently supported are rose(), fell(), and prev().
• There is no support for post-simulation run of assertions (i.e., users cannot run the
assertion engine in post-simulation mode). The Assertions pane is not active in
post-simulation mode either.
• Vprop and vmode in the PSL modeling layer are not supported.
Syntax
PSL assertions are embedded using metacomments prefixed with 'psl'. For example:
-- psl sequence s0 is {b0; b1; b2};
Note that the second line did not require a 'psl' prefix. Once in PSL context, the parser will
remain there until a PSL statement is terminated with a semicolon (';').
Restrictions
Embedded assertions have the following restriction as to where they can be embedded:
• Assertions can be embedded anywhere inside a Verilog module except initial blocks,
always blocks, tasks, and functions. They cannot be embedded in UDPs.
• Assertions can be embedded only in declarative and statement regions of a VHDL entity
or architecture body.
• In a statement region, assertions can appear at places where concurrent statements may
appear. If they appear in a sequential statement, ModelSim will generate an error.
• Assertions cannot be embedded in VHDL procedures and functions.
Example
library IEEE;
use IEEE.std_logic_1164.all;
use IEEE.numeric_std.all;
use WORK.constants.all;
entity dram_control is
generic ( BUG : Boolean := TRUE );
port ( clk : IN std_logic;
reset_n : IN std_logic;
as_n : IN std_logic;
addr_in : IN std_logic_vector(AIN-1 downto 0);
addr_out: OUT std_logic_vector(AOUT-1 downto 0);
rw : IN std_logic; -- 1 to read; 0 to write
we_n : OUT std_logic;
ras_n : OUT std_logic;
cas_n : OUT std_logic;
ack : OUT std_logic );
end entity dram_control;
REF2);
signal mem_state : memory_state := IDLE;
begin
.
.
.
The HDL statements are parsed along with the PSL statements when you compile the
design with vlog/vcom. If you compile the design using vlog/vcom -nopsl, then neither the
HDL statements nor the PSL statements are parsed.
The only place you can't use PSL block meta-comments are in procedural statement
regions.
Syntax
vunit name ([<HDL_design_unit>])
{
default clock = <clock_decl>;
<assertions>;
...
}
Restrictions
The following restrictions exist when providing assertions in a separate file.
• Vunits can be bound only to a module, entity, or architecture.
• The PSL file and its corresponding HDL file must be compiled together.
Example
The following is an example using Verilog syntax that shows three assertions in one vunit.
vunit check_dram_controller(dram_control)
{
default clock = rose(clk);
assert refresh_rate;
assert check_refresh;
assert check_write;
assert check_read;
}
vunit top_vunit(test) {
signal vunit_local_sigA : bit := '0';
signal vunit_loc_sigB : bit := '0';
initial_proc: process
begin
--spy on a signal in a package
init_signal_driver("/pack/global_signal", "vunit_loc_sigA");
--spy on a internal signal
init_signal_driver("/test/aa/internal_signal_AA", "vunit_loc_sigB");
wait;
end process initial_proc;
Here are two points to keep in mind about library and use clauses in PSL files:
• If you already have the use clause applied to an entity, then you don’t need to specify it
for the vunit. The vunit gets the entity's complete visibility.
• If you have two vunits in a file and the use clause at the top, the use clause will apply only
to the top vunit. If you want the use clause to apply to both vunits, you have to specify it
twice. This follows the rules for use clauses as they apply to VHDL entities.
Default clock
Any assertion that is not individually clocked will be clocked by the default clock. For
example:
default clock is rose(clk);
assert always sigb@rose(clk1)
assert always siga;
The first assertion is sensitive to clk1. The second assertion is sensitive to clk (the default
clock).
When using embedded assertions, if you declare an unclocked assertion before defining
default clock, ModelSim produces an error. For example, the following code will produce
an error, assuming there is no other default clock statement above the assertion:
assert always siga;
default clock is rose(clk);
This is not true in the case of assertions located in an external file. The default clock applies
to all unclocked statements regardless of their order within the file.
As noted earlier in "Limitations" (UM-362), default clock declarations are associated with
directives not with named properties or sequences. For example:
default clock is clk1
property p0 is always a->b
default clock is clk2
assert p0
In this case, only the RHS of the implication(|->) expression is clocked. The outermost
property is unclocked, so default clock applies to this assertion.
Also, the complete assertion property must be clocked. For example, if you have the
following assertion:
assert always (b0 |-> (b1@rose(clk1)))
and no default clock preceding it, then since part of the property is unclocked, ModelSim
will produce an error.
In the above property, the @ operator has more precedence than the always operator, so the
property is interpreted like this:
assert always (a -> (b@rose(clk2)) @rose(clk1));
Note that the always operator is unclocked but the property under always is clocked. This
is acceptable because ModelSim detects that the property is to be checked at every
rose(clk1). However, if you also specified a default clock for the assertion:
default clock is rose(clk3);
assert always a -> (b@rose(clk2)) @rose(clk1);
Since the outer operator (always in this case) was left unclocked, it is clocked by the default
clock, and the resulting interpretation is not what you intended to write.
The name generated for this assertion statement will be assert__p0. Generically, the syntax
of the generated name is:
assert__<property name>.
there is no property name, so ModelSim will generate a name like assert__0 (i.e., a number
appended to "assert__" ).
Examples
The following are two complete examples that demonstrate the use of endpoints in Verilog
and VHDL code, respectively.
Verilog
module top;
initial clk_0 = 0;
always #50 clk_0 <= ~clk_0;
initial clk_1 = 0;
always #75 clk_1 <= ~clk_1;
// psl begin
// sequence s0(boolean b_f) = {b1[*2]; [*0:2]; b_f};
// endpoint e0(boolean clk_f) = {s0(b2)@rose(clk_f)};
// end
initial
begin
b1 <= 0; b2 <= 0; //0
#400; b1 <= 1; b2 <= 0; //400
#100; b1 <= 1; b2 <= 1; //500
#200; b1 <= 0; b2 <= 0; //700
#100; b1 <= 0; b2 <= 1; //800
#100; b1 <= 0; b2 <= 0; //900
#300; b1 <= 1; b2 <= 1; //1200
#100; b1 <= 1; b2 <= 0; //1300
#300; b1 <= 0; b2 <= 1; //1600
#300; b1 <= 1; b2 <= 0; //1900
#200; b1 <= 1; b2 <= 1; //2100
#100; b1 <= 0; b2 <= 1; //2200
#100; b1 <= 0; b2 <= 0; //2300
#100; b1 <= 0; b2 <= 1; //2400
#100; b1 <= 0; b2 <= 0; //2500
#100; $finish;
end
initial
$monitor($time, " test_val_0 = %b test_val_1 = %b", test_val_0,
test_val_1);
always @(clk_0)
test_val_0 <= e0(clk_0);
always @(clk_1)
begin
if (e0(clk_1))
test_val_1 <= 1;
else
test_val_1 <= 0;
end
endmodule
VHDL
entity test is
end test;
architecture a of test is
signal clk_0 : bit := '0';
signal clk_1 : bit := '0';
signal b1 : bit := '0';
signal b2 : bit := '0';
begin
-- psl begin
-- sequence s0(Boolean b_f) is {b1[*2]; [*0 to 2]; b_f};
-- endpoint e0(Boolean clk_f) is {s0(b2)}@rose(clk_f);
-- end
endp_0 : process(clk_0)
variable test_val_0 : BOOLEAN;
begin
test_val_0 := e0(clk_0);
end process;
endp_1 : process(clk_1)
variable test_val_1 : bit;
begin
if (e0(clk_1) = true) then
test_val_1 := '1';
else
test_val_1 := '0';
end if;
end process;
process
begin
wait for 400 ns; b1 <= '1'; b2 <= '0'; --400
wait for 100 ns; b1 <= '1'; b2 <= '1'; --500
wait for 200 ns; b1 <= '0'; b2 <= '0'; --700
wait for 100 ns; b1 <= '0'; b2 <= '1'; --800
wait for 100 ns; b1 <= '0'; b2 <= '0'; --900
wait for 300 ns; b1 <= '1'; b2 <= '1'; --1210
wait for 100 ns; b1 <= '1'; b2 <= '0'; --1300
wait for 300 ns; b1 <= '0'; b2 <= '1'; --1600
wait for 300 ns; b1 <= '1'; b2 <= '0'; --1900
wait for 200 ns; b1 <= '1'; b2 <= '1'; --2100
wait for 100 ns; b1 <= '0'; b2 <= '1'; --2200
wait for 100 ns; b1 <= '0'; b2 <= '0'; --2300
wait;
end process;
end a;
Restrictions
• Endpoints are always associated with a clock (see below). Trying to read an endpoint at
a different clock than its own will always result in reading FALSE.
Clocking endpoints
The clock for an endpoint can be specified via the default clock or by using the @clock
operator. For example, both of the following are acceptable:
// psl default clock = rose(clk);
// psl sequence s0 = {b1[*2]; [*0:2]; b2};
// psl endpoint e0 = s0;
or
// psl sequence s0 = {b1[*2]; [*0:2]; b2};
// psl endpoint e0 = {s0}@rose(clk);
Alternatively, the clock can be specified as a parameter to the endpoint and then be passed
at the point of instantiation. For example:
// psl sequence s0 = {b1[*2]; [*0:2]; b2};
// psl endpoint e0(Boolean clk_f) = {s0}@rose(clk_f);
a a a
b b b
c c c
• Keep time ranges specified in sequences as short as possible according to the actual
design property being specified. Avoid long time ranges as this increases the number of
concurrent 'in-flight' checks of the same property and thereby impacts performance.
The design and its associated assertions file must be compiled in the same invocation.
Simulating assertions
If any assertions were compiled, the vsim command (CR-373) automatically invokes the
assertion engine at runtime. If you do not want to simulate the compiled assertions, use the
-nopsl argument.
Managing assertions
You can manage your assertions via the GUI or by entering commands at the VSIM>
prompt.
The Assertions pane lists all embedded and external assertions that were successfully
compiled and simulated during the current session. The plus sign (’+’) to the left of the
Name field lets you expand the assertion hierarchy to show its elements (properties,
sequences, clocks, and HDL signals).
See "Assertions pane columns" (GR-110) for a description of each field.
You can also view this same information in textual format using the assertion report
command (CR-67).
Click here
to enable/
disable
failure or
pass
checking
See "Configure assertions dialog" (GR-114) for more details on this dialog.
You can also enable or disable failure and pass checking using the assertion fail command
(CR-63)or the assertion pass command (CR-65), respectively.
Click here
to enable/
disable
failure or
pass
logging
See "Configure assertions dialog" (GR-114) for more details on this dialog.
You can also enable or disable failure and pass logging using the assertion fail command
or the assertion pass command (CR-65), respectively.
(CR-63)
Click here
to set
failure and
pass limits
See "Configure assertions dialog" (GR-114) for more details on this dialog.
You can also set failure and pass limits using the assertion fail command (CR-63) or the
assertion pass command (CR-65), respectively.
Click here
to select
failure
action
See "Configure assertions dialog" (GR-114) for descriptions of the dialog options.
You can also set failure action using the assertion fail command (CR-63).
Reporting on assertions
Use the assertion report command (CR-67) to print to the transcript a variety of information
about assertions in the current design.
Assertion ’signals’
ModelSim represents assertions as waveforms in the Wave window. The picture below
shows several assertions in a Wave window.
Assertion objects are represented by a magenta triangle. The name of each assertion comes
from the assertion code. The plus sign (’+’) to the left of the name indicates that an assertion
is a composite trace and can be expanded to show its elements (properties, sequences,
clocks, and HDL signals).
The value in the value pane is determined by the active cursor in the waveform pane. The
value will be one of "ACTIVE", "INACTIVE", "PASS" or "FAIL".
The waveform for an assertion represents both continuous and instantaneous information.
The continuous information is whether or not the assertion is active. The assertion is active
anytime it matches the first element in the directive. When active, the trace is raised and
painted green; when inactive it is lowered and painted blue. The instantaneous information
is a pass or fail event on the assertion. These are shown as filled circles above the trace at
the time of the event. A pass is a green circle and a fail is a red circle.
PSL delivers basic functional coverage assessment via the cover directive. With ModelSim
you can monitor, accumulate, and display functional coverage statistics on cover directives.
Introduction
The basic steps for using PSL functional coverage directives in ModelSim are as follows:
1 Write PSL sequences and cover directives that define your functional coverage points.
2 Compile the coverage directives along with your design. See "Compiling and simulating
assertions" (UM-375) for details.
5 View functional coverage statistics either interactively via the GUI or in text-based
reports. See "Viewing functional coverage statistics" (UM-388) below for details.
1 Select View > Debug Windows > Functional Coverage to see your directives in the
Functional Coverage pane.
2 Select Tools > Functional Coverage > Configure or use the fcover configure
command (CR-169).
The configuration dialog lets you enable/disable directive counting and logging, include/
exclude directives from statistics calculation, set a weight for directives, and specify a
minimum number of times a directive should fire. See "Configure cover directives dialog"
(GR-149) for more details.
You can also select directives in the Functional Coverage pane first and then open the
dialog. In that case the "Configure on" section of the dialog is excluded.
Example scenario
The likelihood that each type of bus transaction could be interrupted in a general test is very
low as interrupted transactions are normally rare. You would probably want to ensure that
the design handles the interrupt of all types of transactions and recovers properly from
them. Therefore, you might construct a test such that the stimulus is constrained to ensure
that all types of transactions are generated and that the probability of transactions being
interrupted is relatively high. For that test, the weighting of the interrupted transaction
cover points would probably be higher than the weightings of uninterrupted transactions (or
other coverage criteria).
The pane shows you percentages and a graph for each directive and instance as well as
overall coverage in the status bar at the bottom of the pane. See "Functional Coverage pane"
(GR-143) for a description of each column.
The dialog is described in more detail under "Functional coverage filter dialog" (GR-151).
Note that filtering does not affect the gathering of data nor the calculation of aggregated
statistics. It merely affects the data display.
The table below summarizes the meaning of various parts of the waveform.
Count mode can be useful for gauging the effectiveness of stimulus over time. If all
functional coverage directive counts are static for a long period of time, it may be that the
stimulus is acting in a wasteful manner and can be improved.
The dialog contains a number of options that are described in more detail under "Functional
coverage report dialog" (GR-146).
Here are a couple of points to keep in mind about coverage reporting:
• Filtering doesn't affect the calculation of aggregated statistics. It merely affects the data
displayed in the report.
• A report response of "No match" indicates that the report was empty.
Tag Meaning
Tag Meaning
<numfcovers> gives the number of covers in the design and design unit (if aggregated
coverage is selected in the report)
<du> gives the design unit to which the current cover belongs; this is nested
inside the <cover> tag and thus is distinct from the <designunit> tag
which is at a higher level of hierarchy
<dutype> gives the design unit type for the current cover
Example calculation
Let’s use the following report output to illustrate how the formula works:
Name Design Count AtLeast Weight Status
Unit
/alpha/instance2/coverA beta 6 1 1 Covered
In this case the coverage points in instance1 have twice the weight of the points in
instance2. However, the points in instance1 are not completely covered, so they must
contribute fractionally to the coverage: namely, (6/8) or .75. The points in instance2 are
completely covered, so they contribute the maximum value of 1 to the coverage calculation.
Plugging these values into the formula, we get the following calculation:
( (6/8)*2 + (6/8)*2 + 1 + 1 ) / ( 2 + 2 + 1 + 1 )
= ( 1.5 + 1.5 + 1 + 1 ) / ( 2 + 2 + 1 + 1 )
= 5 / 6
= 0.8333333...
= 83.3%
Limitations
In some circumstances, processing the PSL cover directive will produce too many matches,
causing the cover count to be too high. The problem occurs with coverage of sequences like
{{a;b} | {c;d}} or {a[*1 to 2]; b[*1 to 2]}. In this instance, the same sequence for the same
input at the same start time may succeed simultaneously in multiple ways. The first
sequence may succeed with a and c followed on the next cycle by b and d; this satisfies both
the simultaneous {a;b} and {c;d} sequences. Logically, the evaluation should increment
the count once and only once for a single directive with a given set of inputs from a given
start time. However, in the above example, the Modelsim 6.0 implementation will
increment the count twice.
The dialog is described in more detail under "Functional coverage reload dialog" (GR-145).
Merging details
Here are some details to keep in mind about merging databases:
• Directives in a saved database that aren’t in the current simulation are ignored.
• If there are two identical comments then one of them will be ignored during the merge.
• If there are different "at_least" values for two identical directives then the maximum of
them will be taken for the merge.
• If there are different weights for two identical directives then the maximum of them will
be taken for the merge.
• You can delete or add levels of hierarchy in order to aggregate statistics from different
runs of the same design which were performed in different contexts (e.g., block
simulation vs. chip-level simulation vs. system simulation).
• The reloaded database will replace any currently opened database unless you specify the
Merge into existing data option.
Important: This command clears all data in the database. It is not possible to clear data
for individual directives.
entity test is
end entity test;
architecture t of test is
signal clk : std_logic := '0';
signal a : std_logic := '0';
signal b : std_logic := '0';
begin
clk <= not clk after 50 ns;
process is
begin
wait until clk'event and clk='1'; a<='0'; b<='1';
wait until clk'event and clk='1'; a<='1'; b<='0';
wait until clk'event and clk='1'; a<='1'; b<='1';
wait until clk'event and clk='1'; a<='0'; b<='0';
wait;
end process;
process is
variable L: line;
begin
wait until clk'event and clk='1';
if endpoint_a_after_b=true then
write(L,string'("Endpoint a after b occurred!"));
writeline(output,L);
end if;
end process;
end architecture t;
16 - C Debug
Chapter contents
Introduction . . . . . . . . . . . . . . . UM-400
Supported platforms and gdb versions . . . . . . . . . UM-401
Running C Debug on Windows platforms . . . . . . UM-401
Note: The functionality described in this chapter requires a cdebug license feature in
your ModelSim license file. Please contact your Mentor Graphics sales representative if
you currently do not have such a feature.
Introduction
C Debug allows you to interactively debug FLI/PLI/VPI/SystemC C/C++ source code with
the open-source gdb debugger. Even though C Debug doesn’t provide access to all gdb
features, you may wish to read gdb documentation for additional information.
Please be aware of the following caveats before using C Debug:
• C Debug is an interface to the open-source gdb debugger. We have not customized gdb
source code, and C Debug doesn’t remove any of the limitations or bugs of gdb.
• We assume that you are competent with C or C++ coding and C debugging in general.
• Recommended usage is that you invoke C Debug once for a given simulation and then
quit both C Debug and ModelSim. Starting and stopping C Debug more than once during
a single simulation session may cause problems for gdb.
• The gdb debugger has a known bug that makes it impossible to set breakpoints reliably
in constructors or destructors. Be careful while stepping through code which may end up
calling constructors of SystemC objects; it may crash the debugger.
• Generally you should not have an existing .gdbinit file. If you do, make certain you
haven’t done any of the following: defined your own commands or renamed existing
commands; used 'set annotate...', 'set height...', 'set width...', or 'set print...'; set
breakpoints or watchpoints.
• To use C Debug on Windows platforms, you must compile your source code with gcc/
g++. See "Running C Debug on Windows platforms" (UM-401) below.
32- and 64-bit HP-UX 11.0a, 11.11b wdb version 3.3 or later
a.You must install kernel patch PHKL_22568 (or a later patch that supersedes
PHKL_22568) on HP-UX 11.0. If you do not, you will see the following error
message when trying to enable C Debug:
# Unable to find dynamic library list.
# error from C debugger
b.You must install B.11.11.0306 Gold Base Patches for HP-UX 11i, June
2003.
To invoke C Debug, you must have the following:
• A cdebug license feature; contact Model Technology sales for more information.
• The correct gdb debugger version for your platform.
Setting up C Debug
Before viewing your SystemC/C/C++ source code, you must set up the C Debug path and
options. To set up C Debug, follow these steps:
1 Compile and link your C code with the -g switch (to create debug symbols) and without
-O (or any other optimization switches you normally use). See Chapter 6 - SystemC
simulation for information on compiling and linking SystemC code. See the FLI
Reference Manual or Appendix D - Verilog PLI / VPI / DPI for information on compiling
and linking C code.
2 Specify the path to the gdb debugger by selecting Tools > C Debug > C Debug Setup.
Select "default" to point at the Model Technology supplied version of gdb or "custom"
to point at a separate installation.
3 Start the debugger by selecting Tools > C Debug > Start C Debug. ModelSim will start
the debugger automatically if you set a breakpoint in a SystemC file.
4 If you are not using gcc, or otherwise haven’t specified a source directory, specify a
source directory for your C code with the following command:
ModelSim> gdb dir <srcdirpath1>[:<srcdirpath2>[...]]
In your DO file, add the command cdbg_wait_for_starting to alleviate this problem. For
example:
cdbg enable_auto_step on
cdbg set_debugger /modelsim/5.8c_32/common/linux
cdbg debug_on
cdbg_wait_for_starting
run 10us
Setting breakpoints
Breakpoints in C Debug work much like normal HDL breakpoints. You can create and edit
them with ModelSim commands (bp (CR-75), bd (CR-70), enablebp (CR-158), disablebp
(CR-148)) or via a Source window in the ModelSim GUI (see "File-line breakpoints" (GR-
264)). Some differences do exist:
Clicking the red diamonds with your right (third) mouse button pops up a menu with
commands for removing or enabling/disabling the breakpoints
Note: The gdb debugger has a known bug that makes it impossible to set breakpoints
reliably in constructors or destructors. Do not set breakpoints in constructors of SystemC
objects; it may crash the debugger.
Stepping in C Debug
Stepping in C Debug works much like you would expect. You use the same buttons and
commands that you use when working with an HDL-only design.
Step Tools > C Debug > Run use the step command at the
steps the current simulation to > Step CDBG> prompt
the next statement; if the next
statement is a call to a C function see: step (CR-272) command
that was compiled with debug
info, ModelSim will step into the
function
Step Over Tools > C Debug > Run use the step -over command at the
statements are executed but > Step -Over CDBG> prompt
treated as simple statements
instead of entered and traced see: step (CR-272) command
line-by-line; C functions are not
stepped into unless you have an
enabled breakpoint in the C file
Continue Run Tools > C Debug > Run use the run -continue command at
continue the current simulation > Continue the CDBG> prompt
run until the end of the specified
run length or until it hits a see: run (CR-252)
breakpoint or specified break
event
Example
The graphic below shows a simulation that has stopped at a user-set breakpoint on a PLI
system task.
Because Auto step mode is enabled, ModelSim automatically sets a breakpoint in the
underlying xor_gate.c file. If you click the step button at this point, ModelSim will step into
that file.
1 Start C Debug by selecting Tools > C Debug > Start C Debug before loading your
design.
or
bp -c and_gate_init
ModelSim in turn reports that it has set a breakpoint at line 37 of the and_gate.c file. As
you continue through the design load using run -continue, ModelSim hits that breakpoint
and displays the file and associated line in a Source window.
You can set a breakpoint on the function using either the function name
(i.e., bp -c in_params) or the function pointer (i.e., bp -c *0x4001a950). Note, however, that
foreign functions aren’t called during initialization. You would hit the breakpoint only
during runtime and then only if you enabled the breakpoint after initialization was complete
or had specified Keep user init bps in the C debug setup dialog.
You can set breakpoints on non-null callbacks using the function pointer
(e.g., bp -c *0x40019570). You cannot set breakpoints on null functions. The sizetf and
misctf entries in the example above are null (the function pointer is '0x0').
ModelSim reports the entries in multiples of four with at least one entry each for calltf,
checktf, sizetf, and misctf. Checktf and sizetf functions are called during initialization but
calltf and misctf are not called until runtime.
The second registration method uses init_usertfs functions for each usertfs entry.
ModelSim produces a Transcript message like the following when it encounters an
init_usertfs function during initialization:
# Shared object file './veriuser.sl'
# Function name 'init_usertfs'
# Function ptr '0x40019bec'. Before first call of init_usertfs.
# C breakpoint c.1
# 0x0814fc96 in mti_cdbg_shared_objects_loaded ()
You can set a breakpoint on the function using either the function name
(i.e., bp -c init_usertfs) or the function pointer (i.e., bp -c *0x40019bec). ModelSim will hit
this breakpoint as you continue through initialization.
You can set a breakpoint on the function using the function pointer
(i.e., bp -c *0x4001d310). ModelSim will hit this breakpoint as you continue through
initialization.
With this mode enabled, if you have set a breakpoint in a quit callback function, C Debug
will stop at the breakpoint after you issue the quit command in ModelSim. This allows you
to step and examine the code in the quit callback function.
Invoke run -continue when you are done looking at the C code.
Note that whether or not a C breakpoint was hit, when you return to the VSIM> prompt,
you’ll need to quit C Debug by selecting Tools > C Debug > Quit C Debug before finally
quitting the simulation.
17 - Signal Spy
Chapter contents
Introduction . . . . . . . . . . . . . . . UM-418
Designed for testbenches . . . . . . . . . . . UM-418
init_signal_driver . . . . . . . . . . . . . . UM-419
init_signal_spy . . . . . . . . . . . . . . . UM-422
signal_force . . . . . . . . . . . . . . . UM-425
signal_release . . . . . . . . . . . . . . . UM-427
$init_signal_driver . . . . . . . . . . . . . . UM-429
$init_signal_spy . . . . . . . . . . . . . . UM-432
$signal_force . . . . . . . . . . . . . . . UM-434
$signal_release . . . . . . . . . . . . . . . UM-436
This chapter describes the Signal SpyTM procedures and system tasks. These allow you to
monitor, drive, force, and release hierarchical objects in VHDL or mixed designs.
Introduction
The Verilog language allows access to any signal from any other hierarchical block without
having to route it via the interface. This means you can use hierarchical notation to either
assign or determine the value of a signal in the design hierarchy from a testbench. This
capability fails when a Verilog testbench attempts to reference a signal in a VHDL block
or reference a signal in a Verilog block through a VHDL level of hierarchy.
This limitation exists because VHDL does not allow hierarchical notation. In order to
reference internal hierarchical signals, you have to resort to defining signals in a global
package and then utilize those signals in the hierarchical blocks in question. But, this
requires that you keep making changes depending on the signals that you want to reference.
The Signal Spy procedures and system tasks overcome the aforementioned limitations.
They allow you to monitor (spy), drive, force, or release hierarchical objects in a VHDL or
mixed design.
The VHDL procedures are provided via the "Util package" (UM-96) within the modelsim_lib
library. To access the procedures you would add lines like the following to your VHDL
code:
library modelsim_lib;
use modelsim_lib.util.all;
The Verilog tasks are available as built-in "System tasks and functions" (UM-146). The table
below shows the VHDL procedures and their corresponding Verilog system tasks.
init_signal_driver
The init_signal_driver() procedure drives the value of a VHDL signal or Verilog net (called
the src_object) onto an existing VHDL signal or Verilog net (called the dest_object). This
allows you to drive signals or nets at any level of the design hierarchy from within a VHDL
architecture (e.g., a testbench).
The init_signal_driver procedure drives the value onto the destination signal just as if the
signals were directly connected in the HDL code. Any existing or subsequent drive or force
of the destination signal, by some other means, will be considered with the
init_signal_driver value in the resolution of the signal.
Syntax
init_signal_driver(src_object, dest_object, delay, delay_type, verbose)
Returns
Nothing
Arguments
Related procedures
init_signal_spy (UM-422), In this example, the value of /top/uut/inst1/sig1 is mirrored onto
/top/top_sig1. signal_force (UM-425), signal_release (UM-427)
Limitations
• When driving a Verilog net, the only delay_type allowed is inertial. If you set the delay
type to mti_transport, the setting will be ignored and the delay type will be mti_inertial.
• Any delays that are set to a value less than the simulator resolution will be rounded to the
nearest resolution unit; no special warning will be issued.
Example
library IEEE, modelsim_lib;
use IEEE.std_logic_1164.all;
use modelsim_lib.util.all;
entity testbench is
end;
begin
gen_clk0 : process
begin
clk0 <= '1' after 0 ps, '0' after 20 ps;
wait for 40 ps;
end process gen_clk0;
drive_sig_process : process
begin
init_signal_driver("clk0", "/testbench/uut/blk1/clk", open, open, 1);
init_signal_driver("clk0", "/testbench/uut/blk2/clk", 100 ps,
mti_transport);
wait;
end process drive_sig_process;
...
end;
The above example creates a local clock (clk0) and connects it to two clocks within the
design hierarchy. The .../blk1/clk will match local clk0 and a message will be displayed.
The open entries allow the default delay and delay_type while setting the verbose
parameter to a 1. The .../blk2/clk will match the local clk0 but be delayed by 100 ps.
init_signal_spy
The init_signal_spy() procedure mirrors the value of a VHDL signal or Verilog register/net
(called the src_object) onto an existing VHDL signal or Verilog register (called the
dest_object). This allows you to reference signals, registers, or nets at any level of hierarchy
from within a VHDL architecture (e.g., a testbench).
The init_signal_spy procedure only sets the value onto the destination signal and does not
drive or force the value. Any existing or subsequent drive or force of the destination signal,
by some other means, will override the value that was set by init_signal_spy.
We recommend that you place all init_signal_spy calls in a VHDL process. You need to
code the VHDL process correctly so that it is executed only once. The VHDL process
should not be sensitive to any signals and should contain only init_signal_spy calls and a
simple wait statement. The process will execute once and then wait forever, which is the
desired behavior. See the example below.
Syntax
init_signal_spy(src_object, dest_object, verbose)
Returns
Nothing
Arguments
Related procedures
init_signal_driver (UM-419), In this example, the value of /top/uut/inst1/sig1 is mirrored
onto /top/top_sig1. signal_force (UM-425), signal_release (UM-427)
Limitations
• When mirroring the value of a Verilog register/net onto a VHDL signal, the VHDL signal
must be of type bit, bit_vector, std_logic, or std_logic_vector.
• Verilog memories (arrays of registers) are not supported.
Example
library ieee;
library modelsim_lib;
use ieee.std_logic_1164.all;
use modelsim_lib.util.all;
entity top is
end;
begin
...
spy_process : process
begin
init_signal_spy("/top/uut/inst1/sig1","/top/top_sig1",1,1);
wait;
end process spy_process;
...
spy_enable_disable : process(enable_sig)
begin
if (enable_sig = '1') then
enable_signal_spy("/top/uut/inst1/sig1","/top/top_sig1",0);
elseif (enable_sig = '0')
disable_signal_spy("/top/uut/inst1/sig1","/top/top_sig1",0);
end if;
end process spy_enable_disable;
...
end;
signal_force
The signal_force() procedure forces the value specified onto an existing VHDL signal or
Verilog register or net (called the dest_object). This allows you to force signals, registers,
or nets at any level of the design hierarchy from within a VHDL architecture (e.g., a
testbench).
A signal_force works the same as the force command (CR-180) with the exception that you
cannot issue a repeating force. The force will remain on the signal until a signal_release, a
force or release command, or a subsequent signal_force is issued. Signal_force can be
called concurrently or sequentially in a process.
Syntax
signal_force( dest_object, value, rel_time, force_type, cancel_period,
verbose )
Returns
Nothing
Arguments
Related procedures
init_signal_driver (UM-419), init_signal_spy (UM-422), signal_release (UM-427)
Limitations
You cannot force bits or slices of a register; you can force only the entire register.
Example
library IEEE, modelsim_lib;
use IEEE.std_logic_1164.all;
use modelsim_lib.util.all;
entity testbench is
end;
force_process : process
begin
signal_force("/testbench/uut/blk1/reset", "1", 0 ns, freeze, open, 1);
signal_force("/testbench/uut/blk1/reset", "0", 40 ns, freeze, 2 ms, 1);
wait;
end process force_process;
...
end;
The above example forces reset to a "1" from time 0 ns to 40 ns. At 40 ns, reset is forced
to a "0", 2 ms after the second signal_force call was executed.
If you want to skip parameters so that you can specify subsequent parameters, you need to
use the keyword "open" as a placeholder for the skipped parameter(s). The first
signal_force procedure illustrates this, where an "open" for the cancel_period parameter
means that the default value of -1 ms is used.
signal_release
The signal_release() procedure releases any force that was applied to an existing VHDL
signal or Verilog register/net (called the dest_object). This allows you to release signals,
registers or nets at any level of the design hierarchy from within a VHDL architecture (e.g.,
a testbench).
A signal_release works the same as the noforce command (CR-208). Signal_release can be
called concurrently or sequentially in a process.
Syntax
signal_release( dest_object, verbose )
Returns
Nothing
Arguments
Related procedures
init_signal_driver (UM-419), init_signal_spy (UM-422), In this example, the value of /top/uut/
inst1/sig1 is mirrored onto /top/top_sig1. signal_force (UM-425)
Limitations
• You cannot release a bit or slice of a register; you can release only the entire register.
Example
library IEEE, modelsim_lib;
use IEEE.std_logic_1164.all;
use modelsim_lib.util.all;
entity testbench is
end;
begin
stim_design : process
begin
...
wait until release_flag = '1';
signal_release("/testbench/dut/blk1/data", 1);
signal_release("/testbench/dut/blk1/clk", 1);
...
end process stim_design;
...
end;
The above example releases any forces on the signals data and clk when the signal
release_flag is a "1". Both calls will send a message to the transcript stating which signal
was released and when.
$init_signal_driver
The $init_signal_driver() system task drives the value of a VHDL signal or Verilog net
(called the src_object) onto an existing VHDL signal or Verilog register/net (called the
dest_object). This allows you to drive signals or nets at any level of the design hierarchy
from within a Verilog module (e.g., a testbench).
The $init_signal_driver system task drives the value onto the destination signal just as if
the signals were directly connected in the HDL code. Any existing or subsequent drive or
force of the destination signal, by some other means, will be considered with the
$init_signal_driver value in the resolution of the signal.
Syntax
$init_signal_driver(src_object, dest_object, delay, delay_type, verbose)
Returns
Nothing
Arguments
Related tasks
$init_signal_spy (UM-432), $signal_force (UM-434), $signal_release (UM-436)
Limitations
• When driving a Verilog net, the only delay_type allowed is inertial. If you set the delay
type to 1 (transport), the setting will be ignored, and the delay type will be inertial.
• Any delays that are set to a value less than the simulator resolution will be rounded to the
nearest resolution unit; no special warning will be issued.
• Verilog memories (arrays of registers) are not supported.
Example
`timescale 1 ps / 1 ps
module testbench;
reg clk0;
initial begin
clk0 = 1;
forever begin
#20 clk0 = ~clk0;
end
end
initial begin
$init_signal_driver("clk0", "/testbench/uut/blk1/clk", , , 1);
$init_signal_driver("clk0", "/testbench/uut/blk2/clk", 100, 1);
end
...
endmodule
The above example creates a local clock (clk0) and connects it to two clocks within the
design hierarchy. The .../blk1/clk will match local clk0 and a message will be displayed.
The .../blk2/clk will match the local clk0 but be delayed by 100 ps. For the second call to
work, the .../blk2/clk must be a VHDL based signal, because if it were a Verilog net a 100
ps inertial delay would consume the 40 ps clock period. Verilog nets are limited to only
inertial delays and thus the setting of 1 (transport delay) would be ignored.
$init_signal_spy
The $init_signal_spy() system task mirrors the value of a VHDL signal or Verilog register/
net (called the src_object) onto an existing VHDL signal or Verilog register (called the
dest_object). This allows you to reference signals, registers, or nets at any level of hierarchy
from within a Verilog module (e.g., a testbench).
The $init_signal_spy system task only sets the value onto the destination signal and does
not drive or force the value. Any existing or subsequent drive or force of the destination
signal, by some other means, will override the value set by $init_signal_spy.
Syntax
$init_signal_spy(src_object, dest_object, verbose)
Returns
Nothing
Arguments
Related tasks
$init_signal_driver (UM-429), $signal_force (UM-434), $signal_release (UM-436)
Limitations
• When mirroring the value of a VHDL signal onto a Verilog register, the VHDL signal
must be of type bit, bit_vector, std_logic, or std_logic_vector.
• Verilog memories (arrays of registers) are not supported.
Example
module top;
...
reg top_sig1;
reg enable_reg;
...
initial
begin
$init_signal_spy(".top.uut.inst1.sig1",".top.top_sig1",1,1);
end
...
endmodule
$signal_force
The $signal_force() system task forces the value specified onto an existing VHDL signal
or Verilog register/net (called the dest_object). This allows you to force signals, registers,
or nets at any level of the design hierarchy from within a Verilog module (e.g., a testbench).
A $signal_force works the same as the force command (CR-180) with the exception that you
cannot issue a repeating force. The force will remain on the signal until a $signal_release,
a force or release command, or a subsequent $signal_force is issued. $signal_force can be
called concurrently or sequentially in a process.
Syntax
$signal_force( dest_object, value, rel_time, force_type, cancel_period,
verbose )
Returns
Nothing
Arguments
Related tasks
$init_signal_driver (UM-429), $init_signal_spy (UM-432), $signal_release (UM-436)
Limitations
• You cannot force bits or slices of a register; you can force only the entire register.
• Verilog memories (arrays of registers) are not supported.
Example
`timescale 1 ns / 1 ns
module testbench;
initial
begin
$signal_force("/testbench/uut/blk1/reset", "1", 0, 3, , 1);
$signal_force("/testbench/uut/blk1/reset", "0", 40, 3, 200000, 1);
end
...
endmodule
The above example forces reset to a "1" from time 0 ns to 40 ns. At 40 ns, reset is forced
to a "0", 200000 ns after the second $signal_force call was executed.
$signal_release
The $signal_release() system task releases any force that was applied to an existing VHDL
signal or Verilog register/net (called the dest_object). This allows you to release signals,
registers, or nets at any level of the design hierarchy from within a Verilog module (e.g., a
testbench).
A $signal_release works the same as the noforce command (CR-208). $signal_release can
be called concurrently or sequentially in a process.
Syntax
$signal_release( dest_object, verbose )
Returns
Nothing
Arguments
Related tasks
$init_signal_driver (UM-429), $init_signal_spy (UM-432), $signal_force (UM-434)
Limitations
• You cannot release a bit or slice of a register; you can release only the entire register.
Example
module testbench;
reg release_flag;
...
endmodule
The above example releases any forces on the signals data and clk when the register
release_flag transitions to a "1". Both calls will send a message to the transcript stating
which signal was released and when.
Troubleshooting . . . . . . . . . . . . . . UM-452
Specifying the wrong instance . . . . . . . . . UM-452
Mistaking a component or module name for an instance label . UM-453
Forgetting to specify the instance . . . . . . . . . UM-453
Note: ModelSim will read SDF files that were compressed using gzip. Other
compression formats (e.g., Unix zip) are not supported.
Any number of SDF files can be applied to any instance in the design by specifying one of
the above options for each file. Use -sdfmin to select minimum, -sdftyp to select typical,
and -sdfmax to select maximum timing values from the SDF file.
Instance specification
The instance paths in the SDF file are relative to the instance to which the SDF is applied.
Usually, this instance is an ASIC or FPGA model instantiated under a testbench. For
example, to annotate maximum timing values from the SDF file myasic.sdf to an instance
u1 under a top-level named testbench, invoke the simulator as follows:
vsim -sdfmax /testbench/u1=myasic.sdf testbench
If the instance name is omitted then the SDF file is applied to the top-level. This is usually
incorrect because in most cases the model is instantiated under a testbench or within a
larger system level simulation. In fact, the design can have several models, each having its
own SDF file. In this case, specify an SDF file for each instance. For example,
vsim -sdfmax /system/u1=asic1.sdf -sdfmax /system/u2=asic2.sdf system
You can access this dialog by invoking the simulator without any arguments or by selecting
Simulate > Start Simulation. See the GUI chapter for a description of this dialog.
For Verilog designs, you can also specify SDF files by using the $sdf_annotate system
task. See "The $sdf_annotate system task" (UM-444) for more details.
Resolving errors
If the simulator finds the cell instance but not the generic then an error message is issued.
For example,
** Error (vsim-SDF-3240) myasic.sdf(18):
Instance ’/testbench/dut/u1’ does not have a generic named ’tpd_a_y’
In this case, make sure that the design is using the appropriate VITAL library cells. If it is,
then there is probably a mismatch between the SDF and the VITAL cells. You need to find
the cell instance and compare its generic names to those expected by the annotator. Look
in the VHDL source files provided by the cell library vendor.
If none of the generic names look like VITAL timing generic names, then perhaps the
VITAL library cells are not being used. If the generic names do look like VITAL timing
generic names but don’t match the names expected by the annotator, then there are several
possibilities:
• The vendor’s tools are not conforming to the VITAL specification.
• The SDF file was accidentally applied to the wrong instance. In this case, the simulator
also issues other error messages indicating that cell instances in the SDF could not be
located in the design.
• The vendor’s library and SDF were developed for the older VITAL 2.2b specification.
This version uses different name mapping rules. In this case, invoke vsim (CR-373) with
the -vital2.2b option:
vsim -vital2.2b -sdfmax /testbench/u1=myasic.sdf testbench
Verilog SDF
Verilog designs can be annotated using either the simulator command-line options or the
$sdf_annotate system task (also commonly used in other Verilog simulators). The
command-line options annotate the design immediately after it is loaded, but before any
simulation events take place. The $sdf_annotate task annotates the design at the time it is
called in the Verilog source code. This provides more flexibility than the command-line
options.
Syntax
$sdf_annotate
(["<sdffile>"], [<instance>], ["<config_file>"], ["<log_file>"],
["<mtm_spec>"], ["<scale_factor>"], ["<scale_type>"]);
Arguments
"<sdffile>"
String that specifies the SDF file. Required.
<instance>
Hierarchical name of the instance to be annotated. Optional. Defaults to the instance
where the $sdf_annotate call is made.
"<config_file>"
String that specifies the configuration file. Optional. Currently not supported, this
argument is ignored.
"<log_file>"
String that specifies the logfile. Optional. Currently not supported, this argument is
ignored.
"<mtm_spec>"
String that specifies the delay selection. Optional. The allowed strings are "minimum",
"typical", "maximum", and "tool_control". Case is ignored and the default is
"tool_control". The "tool_control" argument means to use the delay specified on the
command line by +mindelays, +typdelays, or +maxdelays (defaults to +typdelays).
"<scale_factor>"
String that specifies delay scaling factors. Optional. The format is
"<min_mult>:<typ_mult>:<max_mult>". Each multiplier is a real number that is used to
scale the corresponding delay in the SDF file.
"<scale_type>"
String that overrides the <mtm_spec> delay selection. Optional. The <mtm_spec>
delay selection is always used to select the delay scaling factor, but if a <scale_type> is
specified, then it will determine the min/typ/max selection from the SDF file. The
allowed strings are "from_min", "from_minimum", "from_typ", "from_typical",
"from_max", "from_maximum", and "from_mtm". Case is ignored, and the default is
"from_mtm", which means to use the <mtm_spec> value.
Examples
Optional arguments can be omitted by using commas or by leaving them out if they are at
the end of the argument list. For example, to specify only the SDF file and the instance to
which it applies:
$sdf_annotate("myasic.sdf", testbench.u1);
SDF Verilog
The IOPATH construct usually annotates path delays. If ModelSim can’t locate a
corresponding specify path delay, it returns an error unless you use the
+sdf_iopath_to_prim_ok argument to vsim (CR-373). If you specify that argument and the
module contains no path delays, then all primitives that drive the specified output port are
annotated.
SDF Verilog
Both of these constructs identify a module input or inout port and create an internal net that
is a delayed version of the port. This is called a Module Input Port Delay (MIPD). All
primitives, specify path delays, and specify timing checks connected to the original port are
reconnected to the new MIPD net.
SDF Verilog
(PATHPULSE a y (5) (10)) (a => y) = 0;
If the input and output ports are omitted in the SDF, then all path delays are matched in the
cell.
SDF Verilog
If the SDF cell instance is a primitive instance, then that primitive’s delay is annotated. If
it is a module instance, then all specify path delays are annotated that drive the output port
specified in the DEVICE construct (all path delays are annotated if the output port is
omitted). If the module contains no path delays, then all primitives that drive the specified
output port are annotated (or all primitives that drive any output port if the output port is
omitted).
SDF Verilog
SDF Verilog
SDF Verilog
SDF Verilog
(RECOVERY (negedge reset) (posedge clk) (5)) $recovery(negedge reset, posedge clk, 0);
SDF Verilog
(REMOVAL (negedge reset) (posedge clk) (5)) $removal(negedge reset, posedge clk, 0);
SDF Verilog
(RECREM (negedge reset) (posedge clk) (5) (5)) $recovery(negedge reset, posedge clk, 0);
(RECREM (negedge reset) (posedge clk) (5) (5)) $removal(negedge reset, posedge clk, 0);
(RECREM (negedge reset) (posedge clk) (5) (5)) $recrem(negedge reset, posedge clk, 0);
SDF Verilog
(SKEW (posedge clk1) (posedge clk2) (5)) $skew(posedge clk1, posedge clk2, 0);
SDF Verilog
SDF Verilog
SDF Verilog
(NOCHANGE (negedge write) addr (5) (5)) $nochange(negedge write, addr, 0, 0);
SDF Verilog
(SETUP data (posedge clock) (5)) $setup(posedge data, posedge clk, 0);
(SETUP data (posedge clock) (5)) $setup(negedge data, posedge clk, 0);
In this case, the cell accommodates more accurate data than can be supplied by the tool that
created the SDF file, and both timing checks correctly receive the same value.
Likewise, the SDF file may contain more accurate data than the model can accommodate.
SDF Verilog
(SETUP (posedge data) (posedge clock) (4)) $setup(data, posedge clk, 0);
(SETUP (negedge data) (posedge clock) (6)) $setup(data, posedge clk, 0);
In this case, both SDF constructs are matched and the timing check receives the value from
the last one encountered.
Timing check edge specifiers can also use explicit edge transitions instead of posedge and
negedge. However, the SDF file is limited to posedge and negedge. For example,
SDF Verilog
(SETUP data (posedge clock) (5)) $setup(data, edge[01, 0x] clk, 0);
The explicit edge specifiers are 01, 0x, 10, 1x, x0, and x1. The set of [01, 0x, x1] is
equivalent to posedge, while the set of [10, 1x, x0] is equivalent to negedge. A match occurs
if any of the explicit edges in the specify port match any of the explicit edges implied by
the SDF port.
Optional conditions
Timing check ports and path delays can have optional conditions. The annotator uses the
following rules to match conditions:
• A match occurs if the SDF does not have a condition.
• A match occurs for a timing check if the SDF port condition is semantically equivalent
to the specify port condition.
• A match occurs for a path delay if the SDF condition is lexically identical to the specify
condition.
Timing check conditions are limited to very simple conditions, therefore the annotator can
match the expressions based on semantics. For example,
SDF Verilog
(SETUP data (COND (reset!=1) (posedge clock)) (5)) $setup(data, posedge clk &&& (reset==0), 0);
The conditions are semantically equivalent and a match occurs. In contrast, path delay
conditions may be complicated and semantically equivalent conditions may not match. For
example,
SDF Verilog
(COND (r1 || r2) (IOPATH clk q (5))) if (r1 || r2) (clk => q) = 5; // matches
(COND (r1 || r2) (IOPATH clk q (5))) if (r2 || r1) (clk => q) = 5; // does not match
The annotator does not match the second condition above because the order of r1 and r2 are
reversed.
Interconnect delays
An interconnect delay represents the delay from the output of one device to the input of
another. ModelSim can model single interconnect delays or multisource interconnect
delays for Verilog, VHDL/VITAL, or mixed designs. See the vsim command for more
information on the relevant command-line arguments.
Timing checks are performed on the interconnect delayed versions of input ports. This may
result in misleading timing constraint violations, because the ports may satisfy the
constraint while the delayed versions may not. If the simulator seems to report incorrect
violations, be sure to account for the effect of interconnect delays.
tcheck_status (CR-277) prints to the Transcript the current status of one or more timing checks
vlog +notimingchecks disables timing check system tasks for all instances in the specified
Verilog design
vlog +nospecify disables specify path delays and timing checks for all instances in the
specified Verilog design
vsim +no_neg_tchk disables negative timing check limits by setting them to zero for all
instances in the specified design
vsim +no_notifier disables the toggling of the notifier register argument of the timing
check system tasks for all instances in the specified design
vsim +no_tchk_msg disables error messages issued by timing check system tasks when
timing check violations occur for all instances in the specified design
vsim +notimingchecks disables Verilog and VITAL timing checks for all instances in the
specified design
vsim +nospecify disables specify path delays and timing checks for all instances in the
specified design
Troubleshooting
Specifying the wrong instance
By far, the most common mistake in SDF annotation is to specify the wrong instance to the
simulator’s SDF options. The most common case is to leave off the instance altogether,
which is the same as selecting the top-level design unit. This is generally wrong because
the instance paths in the SDF are relative to the ASIC or FPGA model, which is usually
instantiated under a top-level testbench. See "Instance specification" (UM-440) for an
example.
A common example for both VHDL and Verilog testbenches is provided below. For
simplicity, the test benches do nothing more than instantiate a model that has no ports.
VHDL testbench
entity testbench is end;
Verilog testbench
module testbench;
myasic dut();
endmodule
The name of the model is myasic and the instance label is dut. For either testbench, an
appropriate simulator invocation might be:
vsim -sdfmax /testbench/dut=myasic.sdf testbench
The important thing is to select the instance for which the SDF is intended. If the model is
deep within the design hierarchy, an easy way to find the instance name is to first invoke
the simulator without SDF options, view the structure pane, navigate to the model instance,
select it, and enter the environment command (CR-161). This command displays the
instance name that should be used in the SDF command-line option.
Results in:
** Error (vsim-SDF-3250) myasic.sdf(0):
Failed to find INSTANCE ’/testbench/u1’
** Error (vsim-SDF-3250) myasic.sdf(0):
Failed to find INSTANCE ’/testbench/u2’
** Error (vsim-SDF-3250) myasic.sdf(0):
Failed to find INSTANCE ’/testbench/u3’
** Error (vsim-SDF-3250) myasic.sdf(0):
Failed to find INSTANCE ’/testbench/u4’
** Error (vsim-SDF-3250) myasic.sdf(0):
Failed to find INSTANCE ’/testbench/u5’
** Warning (vsim-SDF-3432) myasic.sdf:
This file is probably applied to the wrong instance.
** Warning (vsim-SDF-3432) myasic.sdf:
Ignoring subsequent missing instances from this file.
After annotation is done, the simulator issues a summary of how many instances were not
found and possibly a suggestion for a qualifying instance:
** Warning (vsim-SDF-3440) myasic.sdf:
Failed to find any of the 358 instances from this file.
** Warning (vsim-SDF-3442) myasic.sdf:
Try instance ’/testbench/dut’. It contains all instance paths from this
file.
The simulator recommends an instance only if the file was applied to the top-level and a
qualifying instance is found one level down.
Also see "Resolving errors" (UM-443) for specific VHDL VITAL SDF troubleshooting.
This chapter describes how to use VCD files in ModelSim. The VCD file format is
specified in the IEEE 1364 standard. It is an ASCII file containing header information,
variable definitions, and variable value changes. VCD is in common use for Verilog
designs, and is controlled by VCD system task calls in the Verilog source code. ModelSim
provides command equivalents for these system tasks and extends VCD support to VHDL
designs. The ModelSim commands can be used on VHDL, Verilog, or mixed designs.
If you need vendor-specific ASIC design-flow documentation that incorporates VCD,
please contact your ASIC vendor.
Next, with the design loaded, specify the VCD file name with the vcd file command (CR-
302) and add objects to the file with the vcd add command (CR-292):
VSIM 1> vcd file myvcdfile.vcd
VSIM 2> vcd add /test_counter/dut/*
VSIM 3> run
VSIM 4> quit -f
Next, with the design loaded, specify the VCD file name and objects to add with the vcd
dumpports command (CR-295):
VSIM 1> vcd dumpports -file myvcdfile.vcd /test_counter/dut/*
VSIM 3> run
VSIM 4> quit -f
Case sensitivity
VHDL is not case sensitive so ModelSim converts all signal names to lower case when it
produces a VCD file. Conversely, Verilog designs are case sensitive so ModelSim
maintains case when it produces a VCD file.
1 Create a VCD file for a single design unit using the vcd dumpports command (CR-295).
2 Resimulate the single design unit using the -vcdstim argument to vsim (CR-373). Note
that -vcdstim works only with VCD files that were created by a ModelSim simulation.
Next, rerun the counter without the testbench, using the -vcdstim argument:
% vsim -vcdstim counter.vcd counter
VSIM 1> add wave /*
VSIM 2> run 200
Next, rerun the adder without the testbench, using the -vcdstim argument:
% vsim -vcdstim addern.vcd addern -gn=8 -do "add wave /*; run 1000"
Next, rerun each module separately, using the captured VCD stimulus:
% vsim -vcdstim proc.vcd proc -do "add wave /*; run 1000"
VSIM 1> quit -f
% vsim -vcdstim cache.vcd cache -do "add wave /*; run 1000"
VSIM 1> quit -f
% vsim -vcdstim memory.vcd memory -do "add wave /*; run 1000"
VSIM 1> quit -f
1 Create VCD files for one or more instances in your design using the vcd dumpports
command (CR-295). If necessary, use the -vcdstim switch to handle port order problems
(see below).
Example
In the following example, the three instances /top/p, /top/c, and /top/m are replaced in
simulation by the output values found in the corresponding VCD files.
First, create VCD files for all instances you want to replace:
vcd dumpports -vcdstim -file proc.vcd /top/p/*
vcd dumpports -vcdstim -file cache.vcd /top/c/*
vcd dumpports -vcdstim -file memory.vcd /top/m/*
run 1000
Next, simulate your design and map the instances to the VCD files you created:
vsim top -vcdstim /top/p=proc.vcd -vcdstim /top/c=cache.vcd
-vcdstim /top/m=memory.vcd
The order of the ports in the module line (clk, addr, data, ...) does not match the order
of those ports in the input, output, and inout lines (clk, rdy, addr, ...). In this case the
-vcdstim argument to the vcd dumpports command needs to be used.
In cases where the order is the same, you do not need to use the -vcdstim argument to vcd
dumpports. Also, module declarations of the form:
module proc(input clk, output addr, inout data, ...)
ModelSim versions 5.5 and later also support extended VCD (dumpports system tasks).
The table below maps the VCD dumpports commands to their associated tasks.
ModelSim supports multiple VCD files. This functionality is an extension of the IEEE Std
1364 specification. The tasks behave the same as the IEEE equivalent tasks such as
$dumpfile, $dumpvar, etc. The difference is that $fdumpfile can be called multiple times
to create more than one VCD file, and the remaining tasks require a filename argument to
associate their actions with a specific file.
Important: Note that two commands (vcd file and vcd files) are available to specify a
filename and state mapping for a VCD file. Vcd file allows for only one VCD file and
exists for backwards compatibility with ModelSim versions prior to 5.5. Vcd files allows
for creation of multiple VCD files and is the preferred command to use in ModelSim
versions 5.5 and later.
entity SHIFTER_MOD is
port (CLK, RESET, data_in : IN STD_LOGIC;
Q : INOUT STD_LOGIC_VECTOR(8 downto 0));
END SHIFTER_MOD ;
VCD output
The VCD file created as a result of the preceding scenario would be called output.vcd. The
following pages show how it would look.
VCD output
$date
Thu Sep 18 11:07:43 2003
$end
$version
ModelSim Version 5.8
$end
$timescale
1ns
$end
$scope module shifter_mod $end
$var wire 1 ! clk $end
$var wire 1 " reset $end
$var wire 1 # data_in $end
$var wire 1 $ q [8] $end
$var wire 1 % q [7] $end
$var wire 1 & q [6] $end
$var wire 1 ' q [5] $end
$var wire 1 ( q [4] $end
$var wire 1 ) q [3] $end
$var wire 1 * q [2] $end
$var wire 1 + q [1] $end
$var wire 1 , q [0] $end
$upscope $end
$enddefinitions $end
#0
$dumpvars
0!
1"
0#
0$
0%
0&
0'
0(
0)
0*
0+
0,
$end
#100
1!
#150
0!
#200
1!
$dumpoff
x!
x"
x#
x$
x%
x&
x'
x(
x)
x*
x+
x,
$end
#300
$dumpon
1!
0"
1#
0$
0%
0&
0'
0(
0)
0*
0+
1,
$end
#350
0!
#400
1!
1+
#450
0!
#500
1!
1*
#550
0!
#600
1!
1)
#650
0!
#700
1!
1(
#750
0!
#800
1!
1'
#850
0!
#900
1!
1&
#950
0!
#1000
1!
1%
#1050
0!
#1100
1!
1$
#1150
0!
1"
0,
0+
0*
0)
0(
0'
0&
0%
0$
#1200
1!
$dumpall
1!
1"
1#
0$
0%
0&
0'
0(
0)
0*
0+
0,
$end
D low L low
U high H high
N unknown X unknown
Z tri-state T tri-state
Unknown direction
Unknown direction
Strength values
The <strength> values are based on Verilog strengths:
1 small
2 medium
3 weak
4 large
5 pull ’W’,’H’,’L’
6 strong ’U’,’X’,’0’,’1’,’-’
7 supply
pH 0 6 <7
#20
pD 6 0 <8
#30
pU 0 6 <8
#32
pL 6 0 <7
pH 0 6 <6
#40
pD 6 0 <8
#50
pU 0 6 <8
#52
pH 0 6 <7
#60
pD 6 0 <8
#70
pU 0 6 <8
#72
pL 6 0 <7
pL 6 0 <6
pH 0 6 <5
#80
pD 6 0 <8
#90
pU 0 6 <8
#92
pH 0 6 <7
#100
pD 6 0 <8
$vcdclose
#100
$end
Introduction
This chapter provides an overview of Tcl (tool command language) as used with
ModelSim. Macros in ModelSim are simply Tcl scripts that contain ModelSim and,
optionally, Tcl commands.
Tcl is a scripting language for controlling and extending ModelSim. Within ModelSim you
can develop implementations from Tcl scripts without the use of C code. Because Tcl is
interpreted, development is rapid; you can generate and execute Tcl scripts on the fly
without stopping to recompile or restart ModelSim. In addition, if ModelSim does not
provide the command you need, you can use Tcl to create your own commands.
Tcl References
Two books about Tcl are Tcl and the Tk Toolkit by John K. Ousterhout, published by
Addison-Wesley Publishing Company, Inc., and Practical Programming in Tcl and Tk by
Brent Welch published by Prentice Hall. You can also consult the following online
references:
• Select Help > Tcl Man Pages.
• The Model Technology web site lists a variety of Tcl resources:
www.model.com/resources/tcltk.asp
Tcl commands
For complete information on Tcl commands, select Help > Tcl Man Pages. Also see
"Preference variables located in Tcl files" (UM-540) for information on Tcl variables.
ModelSim command names that conflict with Tcl commands have been renamed or have
been replaced by Tcl commands. See the list below:
format list | wave write format (CR-422) with either list or wave specified
set replaced by the Tcl set command, see "set command syntax"
(UM-477) for more information
1 A Tcl script is a string containing one or more commands. Semi-colons and newlines are
command separators unless quoted as described below. Close brackets ("]") are
command terminators during command substitution (see below) unless quoted.
2 A command is evaluated in two steps. First, the Tcl interpreter breaks the command into
words and performs substitutions as described below. These substitutions are performed
in the same way for all commands. The first word is used to locate a command procedure
to carry out the command, then all of the words of the command are passed to the
command procedure. The command procedure is free to interpret each of its words in
any way it likes, such as an integer, variable name, list, or Tcl script. Different
commands interpret their words differently.
3 Words of a command are separated by white space (except for newlines, which are
command separators).
4 If the first character of a word is a double-quote (""") then the word is terminated by the
next double-quote character. If semi-colons, close brackets, or white space characters
(including newlines) appear between the quotes then they are treated as ordinary
characters and included in the word. Command substitution, variable substitution, and
backslash substitution are performed on the characters between the quotes as described
below. The double-quotes are not retained as part of the word.
5 If the first character of a word is an open brace ("{") then the word is terminated by the
matching close brace ("}"). Braces nest within the word: for each additional open brace
there must be an additional close brace (however, if an open brace or close brace within
the word is quoted with a backslash then it is not counted in locating the matching close
brace). No substitutions are performed on the characters between the braces except for
backslash-newline substitutions described below, nor do semi-colons, newlines, close
brackets, or white space receive any special interpretation. The word will consist of
exactly the characters between the outer braces, not including the braces themselves.
6 If a word contains an open bracket ("[") then Tcl performs command substitution. To do
this it invokes the Tcl interpreter recursively to process the characters following the open
bracket as a Tcl script. The script may contain any number of commands and must be
terminated by a close bracket ("]"). The result of the script (i.e. the result of its last
command) is substituted into the word in place of the brackets and all of the characters
between them. There may be any number of command substitutions in a single word.
Command substitution is not performed on words enclosed in braces.
7 If a word contains a dollar-sign ("$") then Tcl performs variable substitution: the dollar-
sign and the following characters are replaced in the word by the value of a variable.
Variable substitution may take any of the following forms:
$name
Name is the name of a scalar variable; the name is terminated by any character that isn't
a letter, digit, or underscore.
$name(index)
Name gives the name of an array variable and index gives the name of an element within
that array. Name must contain only letters, digits, and underscores. Command
substitutions, variable substitutions, and backslash substitutions are performed on the
characters of index.
${name}
Name is the name of a scalar variable. It may contain any characters whatsoever except
for close braces.
There may be any number of variable substitutions in a single word. Variable substitution
is not performed on words enclosed in braces.
8 If a backslash ("\") appears within a word then backslash substitution occurs. In all cases
but those described below the backslash is dropped and the following character is treated
as an ordinary character and included in the word. This allows characters such as double
quotes, close brackets, and dollar signs to be included in words without triggering special
processing. The following table lists the backslash sequences that are handled specially,
along with the value that replaces each sequence.
9 If a hash character ("#") appears at a point where Tcl is expecting the first character of
the first word of a command, then the hash character and the characters that follow it, up
through the next newline, are treated as a comment and ignored. The comment character
only has significance when it appears at the beginning of a command.
10 Each character is processed exactly once by the Tcl interpreter as part of creating the
words of a command. For example, if variable substitution occurs then no further
substitutions are performed on the value of the variable; the value is inserted into the
word verbatim. If command substitution occurs then the nested command is processed
entirely by the recursive call to the Tcl interpreter; no substitutions are performed before
making the recursive call and no additional substitutions are performed on the result of
the nested script.
11 Substitutions do not affect the word boundaries of a command. For example, during
variable substitution the entire value of the variable becomes part of a single word, even
if the variable's value contains spaces.
if command syntax
The Tcl if command executes scripts conditionally. Note that in the syntax below the "?"
indicates an optional argument.
Syntax
if expr1 ?then? body1 elseif expr2 ?then? body2 elseif ... ?else? ?bodyN?
Description
The if command evaluates expr1 as an expression. The value of the expression must be a
boolean (a numeric value, where 0 is false and anything else is true, or a string value such
as true or yes for true and false or no for false); if it is true then body1 is executed by
passing it to the Tcl interpreter. Otherwise expr2 is evaluated as an expression and if it is
true then body2 is executed, and so on. If none of the expressions evaluates to true then
bodyN is executed. The then and else arguments are optional "noise words" to make the
command easier to read. There may be any number of elseif clauses, including zero. BodyN
may also be omitted as long as else is omitted too. The return value from the command is
the result of the body script that was executed, or an empty string if none of the expressions
was non-zero and there was no bodyN.
Syntax
set varName ?value?
Description
Returns the value of variable varName. If value is specified, then sets the value of varName
to value, creating a new variable if one doesn't already exist, and returns its value. If
varName contains an open parenthesis and ends with a close parenthesis, then it refers to
an array element: the characters before the first open parenthesis are the name of the array,
and the characters between the parentheses are the index within the array. Otherwise
varName refers to a scalar variable. Normally, varName is unqualified (does not include
the names of any containing namespaces), and the variable of that name in the current
namespace is read or written. If varName includes namespace qualifiers (in the array name
if it refers to an array element), the variable in the specified namespace is read or written.
If no procedure is active, then varName refers to a namespace variable (global variable if
the current namespace is the global namespace). If a procedure is active, then varName
refers to a parameter or local variable of the procedure unless the global command was
invoked to declare varName to be global, or unless a Tcl variable command was invoked
to declare varName to be a namespace variable.
Command substitution
Placing a command in square brackets [ ] will cause that command to be evaluated first and
its results returned in place of the command. An example is:
set a 25
set b 11
set c 3
echo "the result is [expr ($a + $b)/$c]"
will output:
"the result is 12"
This feature allows VHDL variables and signals, and Verilog nets and registers to be
accessed using:
[examine -<radix> name]
The %name substitution is no longer supported. Everywhere %name could be used, you
now can use [examine -value -<radix> name] which allows the flexibility of specifying
command options. The radix specification is optional.
Command separator
A semicolon character (;) works as a separator for multiple commands on the same line. It
is not required at the end of a line in a command sequence.
Multiple-line commands
With Tcl, multiple-line commands can be used within macros and on the command line.
The command line prompt will change (as in a C shell) until the multiple-line command is
complete.
In the example below, note the way the opening brace ’{’ is at the end of the if and else
lines. This is important because otherwise the Tcl scanner won't know that there is more
coming in the command and will try to execute what it has up to that point, which won't be
what you intend.
if { [exa sig_a] == "0011ZZ"} {
echo "Signal value matches"
do macro_1.do
} else {
echo "Signal value fails"
do macro_2.do
}
Evaluation order
An important thing to remember when using Tcl is that anything put in curly brackets {} is
not evaluated immediately. This is important for if-then-else statements, procedures, loops,
and so forth.
• For the equal operator, you must use the C operator "==". For not-equal, you must use
the C operator "!=".
Variable substitution
When a $<var_name> is encountered, the Tcl parser will look for variables that have been
defined either by ModelSim or by you, and substitute the value of the variable.
See "Simulator state variables" (UM-542) for more information about ModelSim-defined
variables.
System commands
To pass commands to the UNIX shell or DOS window, use the Tcl exec command:
echo The date is [exec date]
List processing
In Tcl a "list" is a set of strings in curly braces separated by spaces. Several Tcl commands
are available for creating lists, indexing into lists, appending to lists, getting the length of
lists and shifting lists. These commands are:
lappend var_name val1 val2 ... appends val1, val2, etc. to list var_name
lindex list_name index returns the index-th element of list_name; the first element is 0
linsert list_name index val1 val2 ... inserts val1, val2, etc. just before the index-th element of list_name
list val1, val2 ... returns a Tcl list consisting of val1, val2, etc.
lreplace list_name first last val1, val2, ... replaces elements first through last with val1, val2, etc.
Two other commands, lsearch and lsort, are also available for list manipulation. See the
Tcl man pages (Help > Tcl Man Pages) for more information on these commands.
See also the ModelSim Tcl command: lecho (CR-188)
Command Description
alias (CR-62) creates a new Tcl procedure that evaluates the specified commands;
used to create a user-defined alias
lshift (CR-193) takes a Tcl list as argument and shifts it in-place one place to the left,
eliminating the 0th element
lsublist (CR-194) returns a sublist of the specified Tcl list that matches the specified
Tcl glob pattern
printenv (CR-224) echoes to the Transcript pane the current names and values of all
environment variables
Conversions
Command Description
intToTime <intHi32> <intLo32> converts two 32-bit pieces (high and low
order) into a 64-bit quantity (Time in
ModelSim is a 64-bit integer)
Relations
Command Description
All relation operations return 1 or 0 for true or false respectively and are suitable return
values for TCL conditional expressions. For example,
if {[eqTime $Now 1750ns]} {
...
}
Arithmetic
Command Description
Tcl examples
This is an example of using the Tcl while loop to copy a list from variable a to variable b,
reversing the order of the elements along the way:
set b [list]
set i [expr {[llength $a] - 1}]
while {$i >= 0} {
lappend b [lindex $a $i]
incr i -1
}
This example uses the Tcl for command to copy a list from variable a to variable b,
reversing the order of the elements along the way:
set b [list]
for {set i [expr {[llength $a] - 1}]} {$i >= 0} {incr i -1} {
lappend b [lindex $a $i]
}
This example uses the Tcl foreach command to copy a list from variable a to variable b,
reversing the order of the elements along the way (the foreach command iterates over all of
the elements of a list):
set b [list]
foreach i $a { set b [linsert $b 0 $i] }
This example shows a list reversal as above, this time aborting on a particular element using
the Tcl break command:
set b [list]
foreach i $a {
if {$i = "ZZZ"} break
set b [linsert $b 0 $i]
}
This example is a list reversal that skips a particular element by using the Tcl continue
command:
set b [list]
foreach i $a {
if {$i = "ZZZ"} continue
set b [linsert $b 0 $i]
}
The next example works in UNIX only. In a Windows environment, the Tcl exec command
will execute compiled files only, not system commands.) The example shows how you can
access system information and transfer it into VHDL variables or signals and Verilog nets
or registers. When a particular HDL source breakpoint occurs, a Tcl function is called that
gets the date and time and deposits it into a VHDL signal of type STRING. If a particular
environment variable (DO_ECHO) is set, the function also echoes the new date and time
to the transcript file by examining the VHDL variable.
(in VHDL source):
signal datime : string(1 to 28) := " ";# 28 spaces
This next example shows a complete Tcl script that restores multiple Wave windows to
their state in a previous simulation, including signals listed, geometry, and screen position.
It also adds buttons to the Main window toolbar to ease management of the wave files.
## This file contains procedures to manage multiple wave files.
## Source this file from the command line or as a startup script.
## source <path>/wave_mgr.tcl
## add_wave_buttons
## Add wave management buttons to the main toolbar (new, save and load)
## new_wave
## Dialog box creates a new wave window with the user provided name
## named_wave <name>
## Creates a new wave window with the specified title
## save_wave <file-root>
## Saves name, window location and contents for all open windows
## wave windows
## Creates <file-root><n>.do file for each window where <n> is 1
## to the number of windows. Default file-root is "wave". Also
## creates windowSet.do file that contains title and geometry info.
## load_wave <file-root>
## Opens and loads wave windows for all files matching <file-root><n>.do
## where <n> are the numbers from 1-9. Default <file-root> is "wave".
## Also runs windowSet.do file if it exists.
proc add_wave_buttons {} {
_add_menu main controls right SystemMenu SystemWindowFrame {Load Waves} \
load_wave
_add_menu main controls right SystemMenu SystemWindowFrame {Save Waves} \
save_wave
_add_menu main controls right SystemMenu SystemWindowFrame {New Wave} \
new_wave
}
## Simple Dialog requests name of new wave window. Defaults to Wave<n>
proc new_wave {} {
global vsimPriv
set defaultName "Wave[llength $vsimPriv(WaveWindows)]"
set windowName [GetValue . "Create Named Wave Window:" $defaultName ]
if {$windowName == ""} {
# Dialog canceled
# abort operation
return
}
## Debug
puts "Window name: $windowName\n"
if {$windowName == "{}"} {
set windowName ""
}
if {$windowName != ""} {
named_wave $windowName
} else {
named_wave $defaultName
}
}
## Creates a new wave window with the provided name (defaults to "Wave")
## Writes out format of all wave windows, stores geometry and title info in
## windowSet.do file. Removes any extra files with the same fileroot.
## Default file name is wave<n> starting from 1.
}
}
}
## Provide file root argument and load_wave restores all saved windows.
## Default file root is "wave".
...
This next example specifies the compiler arguments and lets you compile any number of
files.
set Files [list]
set nbrArgs $argc
for {set x 1} {$x <= $nbrArgs} {incr x} {
set lappend Files $1
shift
}
eval vcom -93 -explicit -noaccel $Files
This example is an enhanced version of the last one. The additional code determines
whether the files are VHDL or Verilog and uses the appropriate compiler and arguments
depending on the file type. Note that the macro assumes your VHDL files have a .vhd file
extension.
set vhdFiles [list]
set vFiles [list]
set nbrArgs $argc
for {set x 1} {$x <= $nbrArgs} {incr x} {
if {[string match *.vhd $1]} {
lappend vhdFiles $1
} else {
lappend vFiles $1
}
shift
}
if {[llength $vhdFiles] > 0} {
eval vcom -93 -explicit -noaccel $vhdFiles
}
if {[llength $vFiles] > 0} {
eval vlog $vFiles
}
Creating DO files
You can create DO files, like any other Tcl script, by typing the required commands in any
editor and saving the file. Alternatively, you can save the transcript as a DO file (see
"Saving the transcript file" (GR-16)).
All "event watching" commands (e.g. onbreak (CR-214), onerror (CR-216), etc.) must be
placed before run (CR-252) commands within the macros in order to take effect.
The following is a simple DO file that was saved from the transcript. It is used in the dataset
exercise in the ModelSim Tutorial. This DO file adds several signals to the Wave window,
provides stimulus to those signals, and then advances the simulation.
add wave ld
add wave rst
add wave clk
add wave d
add wave q
force -freeze clk 0 0, 1 {50 ns} -r 100
force rst 1
force rst 0 10
force ld 0
force d 1010
onerror {cont}
run 1700
force ld 1
run 100
force ld 0
run 400
force rst 1
run 200
force rst 0 10
run 1500
There is no limit on the number of parameters that can be passed to macros, but only nine
values are visible at one time. You can use the shift command (CR-266) to see the other
parameters.
The first line will close the current log file. The second will open a new log file. If it has
the same name as an existing file, it will replace the previous one.
Example 1
This macro specifies the files to compile and handles 0-2 compiler arguments as
parameters. If you supply more arguments, ModelSim generates a message.
switch $argc {
0 {vcom file1.vhd file2.vhd file3.vhd }
1 {vcom $1 file1.vhd file2.vhd file3.vhd }
2 {vcom $1 $2 file1.vhd file2.vhd file3.vhd }
default {echo Too many arguments. The macro accepts 0-2 args. }
}
Example 2
This macro specifies the compiler arguments and lets you compile any number of files.
variable Files ""
set nbrArgs $argc
for {set x 1} {$x <= $nbrArgs} {incr x} {
set Files [concat $Files $1]
shift
}
eval vcom -93 -explicit -noaccel $Files
Example 3
This macro is an enhanced version of the one shown in example 2. The additional code
determines whether the files are VHDL or Verilog and uses the appropriate compiler and
arguments depending on the file type. Note that the macro assumes your VHDL files have
a .vhd file extension.
variable vhdFiles ""
variable vFiles ""
set nbrArgs $argc
set vhdFilesExist 0
set vFilesExist 0
for {set x 1} {$x <= $nbrArgs} {incr x} {
if {[string match *.vhd $1]} {
set vhdFiles [concat $vhdFiles $1]
set vhdFilesExist 1
} else {
set vFiles [concat $vFiles $1]
set vFilesExist 1
}
shift
}
if {$vhdFilesExist == 1} {
eval vcom -93 -explicit -noaccel $vhdFiles
}
if {$vFilesExist == 1} {
eval vlog $vFiles
}
command result
run (CR-252) -continue continue as if the breakpoint had not been executed, completes
the run (CR-252) that was interrupted
onbreak (CR-214) specify a command to run when you hit a breakpoint within a
macro
abort (CR-44) terminate a macro once the macro has been interrupted or
paused
pause (CR-217) cause the macro to be interrupted; the macro can be resumed by
entering a resume command (CR-249) via the command line
Note: You can also set the OnErrorDefaultAction Tcl variable (see "Preference variables
located in Tcl files" (UM-540)) in the pref.tcl file to dictate what action ModelSim takes
when an error occurs.
1 If an onerror (CR-216) command has been set in the macro script, ModelSim executes
that command. The onerror (CR-216) command must be placed prior to the run
command in the DO file to take effect.
2 If no onerror command has been specified in the script, ModelSim checks the
OnErrorDefaultAction Tcl variable. If the variable is defined, its action will be
invoked.
Macro helper
This tool is available for UNIX only (excluding Linux).
The purpose of the Macro Helper is to aid macro creation by recording a simple series of
mouse movements and key strokes. The resulting file can be called from a more complex
macro by using the play (CR-218) command. Actions recorded by the Macro Helper can
only take place within the ModelSim GUI (window sizing and repositioning are not
recorded because they are handled by your operating system’s window manager). In
addition, the run (CR-252) commands cannot be recorded with the Macro Helper but can be
invoked as part of a complex macro.
Select Tools > Macro Helper to access
the Macro Helper.
• Record a macro
by typing a new macro file name into
the field provided and pressing Record.
• Play a macro
by entering the file name of a Macro
Helper file into the field and pressing Play.
Files created by the Macro Helper can be viewed with the notepad (CR-211).
See "Macro dialog" (GR-102) for more details on the dialog. See the macro_option
command (CR-195) for playback speed, delay, and debugging options for completed macro
files.
How it works
TDebug works by parsing and redefining Tcl/Tk-procedures, inserting calls to `td_eval' at
certain points, which takes care of the display, stepping, breakpoints, variables etc. The
advantages are that TDebug knows which statement in which procedure is currently being
executed and can give visual feedback by highlighting it. All currently accessible variables
and their values are displayed as well. Code can be evaluated in the context of the current
procedure. Breakpoints can be set and deleted with the mouse.
Unfortunately there are drawbacks to this approach. Preparation of large procedures is slow
and due to Tcl's dynamic nature there is no guarantee that a procedure can be prepared at
all. This problem has been alleviated somewhat with the introduction of partial preparation
of procedures. There is still no possibility to get at code running in the global context.
The Chooser
Select Tools > Tcl Debugger to open the TDebug chooser.
The TDebug chooser has three parts. At
the top the current interpreter, vsim.op_,
is shown. In the main section there are
two list boxes. All currently defined
procedures are shown in the left list
box. By clicking the left mouse button
on a procedure name, the procedure
gets prepared for debugging and its
name is moved to the right list box.
Clicking a name in the right list box
returns a procedure to its normal state.
Press the right mouse button on a
procedure in either list box to get its
program code displayed in the main
debugger window.
The three buttons at the bottom let you
force a Rescan of the available
procedures, Popup the debugger window or Exit TDebug. Exiting from TDebug doesn't
terminate ModelSim, it merely detaches from vsim.op_, restoring all prepared procedures
to their unmodified state.
The Debugger
Select the Popup button in the Chooser to open the debugger window.
The debugger window is divided into the main region with the name of the current
procedure (Proc), a listing in which the expression just executed is highlighted, the Result
of this execution and the currently available Variables and their values, an entry to Eval
expressions in the context of the current procedure, and some button controls for the state
of the debugger.
A procedure listing displayed in the main region will have a darker background on all lines
that have been prepared. You can prepare or restore additional lines by selecting a region
(<Button-1>, standard selection) and choosing Selection > Prepare Proc or Selection >
Restore Proc from the debugger menu (or by pressing ^P or ^R).
When using `Prepare' and `Restore', try to be smart about what you intend to do. If you
select just a single word (plus some optional white space) it will be interpreted as the name
of a procedure to prepare or restore. Otherwise, if the selection is owned by the listing, the
corresponding lines will be used.
Be careful with partial prepare or restore! If you prepare random lines inside a `switch' or
`bind' expression, you may get surprising results on execution, because the parser doesn't
know about the surrounding expression and can't try to prevent problems.
There are seven possible debugger states, one for each button and an `idle' or `waiting' state
when no button is active. The button-activated states are:
Button Description
Closing the debugger doesn't quit it, it only does `wm withdraw'. The debugger window
will pop up the next time a prepared procedure is called. Make sure you close the debugger
with Debugger > Close.
Breakpoints
To set/unset a breakpoint, double-click inside the listing. The breakpoint will be set at the
innermost available expression that contains the position of the click. Conditional or
counted breakpoints aren’t supported.
The Eval entry supports a simple history mechanism available via the <Up_arrow> and
<Down_arrow> keys. If you evaluate a command while stepping through a procedure, the
command will be evaluated in the context of the procedure; otherwise it will be evaluated
at the global level. The result will be displayed in the result field. This entry is useful for a
lot of things, but especially to get access to variables outside the current scope.
Configuration
You can customize TDebug by setting up a file named .tdebugrc in your home directory.
See the TDebug README at Help > Technotes > tdebug for more information on the
configuration of TDebug.
TclPro Debugger
The Tools menu in the Main window contains a selection for the TclPro Debugger from
Scriptics Corporation. This debugger and any available documentation can be acquired
from Scriptics. Once acquired, do the following steps to use the TclPro Debugger:
4 Press the Stop button in the debugger in order to set breakpoints, etc.
Note: TclPro Debugger version 1.4 does not work with ModelSim.
ModelSim 6.0 includes many new GUI features and enhancements that are described in this
document. Links within the sections will connect you to more detail.
See "Customizing the GUI layout" (GR-258) for more information on this and other methods
for changing the view of GUI panes and windows.
Object name
Context Sensitivity
In 6.0, the number of menu items which are context-sensitive has increased substantially.
If an item is grayed-out, it is not available in the current context. In general, you can activate
a grayed-out menu item by activating the associated pane/window.
File menu
The File menu has several additions and changes. This section presents and illustrates the
changes in the File menu from 5.8 to 6.0.
For complete details on all new 6.0 menu items, refer to "Main window" (GR-14).
• File > New > Window becomes View > Debug Windows
This submenu changes significantly. All windows/panes not specifically discussed or
highlighted remain the same.
5.8 File > New > Window 6.0 View > Debug Windows
Edit >
View menu
The View menu has been rearranged a bit, but all the items remain.
• View All Windows... becomes View > Debug Windows > All Windows...
A sub menu is added to the View menu for all debug windows. For the name changes of
the windows, see "Main window changes" (UM-500).
See "Main window menu bar" (GR-20) for complete menu option details.
Simulate menu
The Simulate menu has incorporated the following changes:
• Design Optimization
You can now gain access to ModelSim’s design optimization features through the
Simulate > Design Optimization. For more information, see "Design Optimization
dialog" (GR-70).
• Simulate > Simulate becomes Simulate > Start Simulation
• Simulate > Simulate Options becomes Simulate > Runtime Options
These changes are in name only. The associated dialog boxes remain functionally the same.
Tools menu
The 6.0 Main window Tools menu changes as follows:
• Coverage becomes Code Coverage
• Profile > Profile On / Profile Off becomes Profile > Performance (toggles on and off
with selection)
• Profile > View hierarchical profile and View ranked profile become Call Tree and
Ranked tabs in the Profile window
5.8 Tools > Profile > 6.0 Tools > Profile >
See "Main window menu bar" (GR-20) for complete menu option details.
Window menu
The 6.0 Window menu removes one selection:
• Window > Layout Style
The window layout styles available in 5.8 have been replaced by the 6.0 MDI (Multiple
Document Interface) system. You can easily move panes by dragging and dropping.
Moving panes
around by left-
clicking on top of
pane, dragging and
dropping where
desired.
5.8 List window > File 6.0 List window > File
5.8
6.0
File menu
The Memory window > File menu changes as follows:
• File > Environment menu selection removed
• File > Close Instance and Close All
Right-click anywhere in memory contents pane for menu selections.
5.8 Memory window > File > 6.0 Main Menu > File >
Right-click in mem
pane, in either the
address or data
areas.
Edit menu
The Memory window > Edit menu changes as follows:
• Edit > Goto accessible through right-click in address area
• Edit > Change, Find, and Data Search accessible through right-click in data area
5.8 Memory window > Edit > 6.0 Right-click in the address area of
the memory contents (mem) pane.
View menu
The Memory window > View menu changes as follows:
• View > Memory Declaration accessible through right-click on memory instance
• View > Split Screen accessible through right-click in address area of memory contents
pane
5.8 Memory window > View > 6.0 Right-click on selected memory
instance within the Workspace pane
File menu
The Signals window > File menu changes as follows:
• File > New Window is not supported
• File > Save List becomes File > Report
5.8 Signals window > File 6.0 Main window (with Objects pane active) > File
Multiple Objects
windows not
supported in 6.0.
Edit menu
The Signals window > Edit menu changes as follows:
• Edit > Expand/Collapse menu selections become Main window > Edit > Expand >
Expand Selected, Collapse Selected, Expand All, and Collapse All
• Edit > Force, NoForce, and Clock become Main window > Edit > Advanced > Force,
NoForce, and Clock
5.8 Source window > Edit 6.0 Main window > Edit > Expand
> Advanced
(sub-menus)
File menu
The Source window > File menu changes as follows:
• File > Open Design Source is accessible through Main window Workspace > File tab
5.8 Source window > File 6.0 Main window > File tab in Workspace pane
View menu
The Source window > File menu changes as follows:
• View > Show line numbers / language templates is accessible through View > Source
5.8 Source window > File 6.0 Main window > File tab
Edit menu
The Variables window > Edit menu changes as follows:
• Edit > Expand/Collapse menu selections become Main window > Edit > Expand >
Expand Selected, Collapse Selected, Expand All, and Collapse All
• Edit > Change becomes Main window > Edit > Advanced > Change
5.8 Locals window > Edit 6.0 Main window > Edit > Expand
> Advanced
B - ModelSim variables
Appendix contents
Variable settings report . . . . . . . . . . . . UM-520
Personal preferences . . . . . . . . . . . . . UM-520
The simulator control variables reported by the report simulator control command can be
set interactively using the Tcl set command (UM-477).
Personal preferences
There are several preferences stored by ModelSim on a personal basis, independent of
modelsim.ini or modelsim.tcl files. These preferences are stored in $(HOME)/.modelsim on
UNIX and in the Windows Registry under HKEY_CURRENT_USER\Software\Model
Technology Incorporated\ModelSim. Among these preferences are:
• mti_ask_LBViewTypes, mti_ask_LBViewPath, mti_ask_LBViewLoadable
Settings for the Customize Library View dialog. Determine the view of the Library tab
in the Workspace pane.
• mti_pane_cnt, mti_pane_size, pane_#, pane_percent
Determine the layout of various panes in the Main window.
• open_workspace
Setting for whether or not to display the Workspace pane.
• pinit
Project Initialization state (one of: Welcome | OpenLast | NoWelcome). This determines
whether the Welcome To ModelSim dialog box appears when you invoke the tool.
• project_history
Project history.
• printersetup
All setup parameters related to printing (i.e., current printer, etc.).
• transcriptpercent
The size of the Transcript pane. Expressed as a percentage of the width of the Main
window.
The HKEY_CURRENT_USER key is unique for each user Login on Windows NT.
Environment variables
Before compiling or simulating, several environment variables may be set to provide the
functions described in the table below. The variables are in the autoexec.bat file on
Windows 98/Me machines, and set through the System control panel on NT/2000/XP
machines. For UNIX, the variables are typically found in the .login script. The
LM_LICENSE_FILE variable is required; all others are optional.
Variable Description
The DOPATH environment variable isn’t accessible when you invoke vsim from
a Unix shell or from a Windows command prompt. It is accessible once ModelSim
or vsim is invoked. If you need to invoke from a shell or command line and use
the DOPATH environment variable, use the following syntax:
EDITOR specifies the editor to invoke with the edit command (CR-157)
HOME used by ModelSim to look for an optional graphical preference file and optional
location map file; see: "Preference variables located in INI files" (UM-524)
LM_LICENSE_FILE used by the ModelSim license file manager to find the location of the license file;
may be a colon-separated (semi-colon for Windows) set of paths, including paths
to other vendor license files; REQUIRED
MODEL_TECH set by all ModelSim tools to the directory in which the binary executable resides;
DO NOT SET THIS VARIABLE!
MODEL_TECH_TCL used by ModelSim to find Tcl libraries for Tcl/Tk 8.3 and vsim; may also be used
to specify a startup DO file; defaults to /modeltech/../tcl; may be set to an alternate
path
MGC_LOCATION_MAP used by ModelSim tools to find source files based on easily reallocated "soft"
paths; optional; see the Tcl variables: SourceDir and SourceMap
MODELSIM used by all ModelSim tools to find the modelsim.ini file; consists of a path
including the file name. An alternative use of this variable is to set it to the path of
a project file (<Project_Root_Dir>/<Project_Name>.mpf). This allows you to
use project settings with command line tools. However, if you do this, the .mpf
file will replace modelsim.ini as the initialization file for all ModelSim tools.
MODELSIM_TCL used by ModelSim to look for an optional graphical preference file; can be a
colon-separated (UNIX) or semi-colon separated (Windows) list of file paths
MTI_COSIM_TRACE creates an mti_trace_cosim file containing debugging information about FLI/PLI/
VPI function calls; set to any value before invoking the simulator.
Variable Description
MTI_TF_LIMIT limits the size of the VSOUT temp file (generated by the ModelSim kernel); the
value of the variable is the size of k-bytes; TMPDIR (below) controls the location
of this file, STDOUT controls the name; default = 10, 0 = no limit; does not
control the size of the transcript file
MTI_USELIB_DIR specifies the directory into which object libraries are compiled when using the
-compile_uselibs argument to the vlog command (CR-358)
MTI_VCO_MODE determines which version of ModelSim to use on platforms that support both 32-
and 64-bit versions when ModelSim executables are invoked from the modeltech/
bin directory by a Unix shell command (using full path specification or PATH
search); if MTI_VCO_MODE is not set, the preference is given to the highest
performance installed version
NOMMAP if set to 1, disables memory mapping in ModelSim; this should be used only when
running on Linux 7.1; it will decrease the speed with which ModelSim reads files
PLIOBJS used by ModelSim to search for PLI object files for loading; consists of a
space-separated list of file or path names
STDOUT the VSOUT temp file (generated by the simulator kernel) is deleted when the
simulator exits; the file is not deleted if you specify a filename for VSOUT with
STDOUT; specifying a name and location (use TMPDIR) for the VSOUT file will
also help you locate and delete the file in event of a crash (an unnamed VSOUT
file is not deleted after a crash either)
TMPDIR (Unix) specifies the path to a tempnam() generated file (VSOUT) containing all stdout
TMP (Windows) from the simulation kernel
If you used DOS vmap, this line will be added to the modelsim.ini:
MY_VITAL = c:\temp\work
If vmap is used from the ModelSim/VSIM prompt, the modelsim.ini file will be modified
with this line:
MY_VITAL = $MY_PATH
You can easily add additional hierarchy to the path. For example,
vmap MORE_VITAL %MY_PATH%\more_path\and_more_path
vmap MORE_VITAL \$MY_PATH\more_path\and_more_path
The "$" character in the examples above is Tcl syntax that precedes a variable. The "\"
character is an escape character that keeps the variable from being evaluated during the
execution of vmap.
Environment variables may also be referenced from the ModelSim command line or in
macros using the Tcl env array mechanism:
echo "$env(ENV_VAR_NAME)"
Note: Environment variable expansion does not occur in files that are referenced via the
-f argument to vcom, vlog, or vsim.
ieee any valid path; may include sets the path to the library containing IEEE and
environment variables Synopsys arithmetic packages; the default is
$MODEL_TECH/../ieee
modelsim_lib any valid path; may include sets the path to the library containing Model
environment variables Technology VHDL utilities such as Signal Spy;
the default is $MODEL_TECH/../modelsim_lib
std any valid path; may include sets the path to the VHDL STD library; the default
environment variables is $MODEL_TECH/../std
std_developerskit any valid path; may include sets the path to the libraries for MGC standard
environment variables developer’s kit; the default is
$MODEL_TECH/../std_developerskit
synopsys any valid path; may include sets the path to the accelerated arithmetic
environment variables packages; the default is $MODEL_TECH/../
synopsys
verilog any valid path; may include sets the path to the library containing VHDL/
environment variables Verilog type mappings; the default is
$MODEL_TECH/../verilog
vital2000 any valid path; may include sets the path to the VITAL 2000 library; the
environment variables default is $MODEL_TECH/../vital2000
others any valid path; may include points to another modelsim.ini file whose library
environment variables path variables will also be read; the pathname
must include "modelsim.ini"; only one others
variable can be specified in any modelsim.ini file.
SparseMemThreshhold natural the size at which memories will automatically be off (0)
integer marked as sparse memory; see "Sparse memory
(>=0) modeling" (UM-156)
CppOptions any valid adds any specified C++ compiler options to the none
C+++ sccom command line at the time of invocation
compiler
options
CppPath C++ If used, variables should point directly to the location none
compiler of the g++ executable, such as:
path % CppPath /usr/bin/g++
This variable is not required when running SystemC
designs. By default, you should install and use the
built-in g++ compiler that comes with ModelSim
UseScv 0, 1 if 1, turns on use of SCV include files and library; off (0)
see"-scv" (CR-255) for details
AssertFile any valid alternative file for storing VHDL or PSL transcript
filename assertion messages
AssertionFailAction 0, 1, 2 sets action for a PSL failure event; use 0 for continue (0)
continue, 1 for break, 2 for exit
AssertionFailEnable 0, 1 turns on failure tracking for PSL assertions on (1)
AssertionFormat see next column defines format of VHDL assertion "** %S:
messages; fields include: %R\n Time:
%S - severity level %T
%R - report message Iteration:
%T - time of assertion %D%I\n"
%D - delta
%I - instance or region pathname (if
available)
%i - instance pathname with process
%O - process name
%K - kind of object path points to; returns
Instance, Signal, Process, or Unknown
%P - instance or region path without leaf
process
%F - file
%L - line number of assertion, or if from
subprogram, line from which call is made
%% - print ’%’ character
AssertionFormatBreak see defines format of messages for VHDL "** %S:
AssertionFormat assertions that trigger a breakpoint; see %R\n
above AssertionFormat for options Time: %T
Iteration:
%D %K: %i
File: %F\n"
AssertionFormatFail see defines format of messages for VHDL Fail "** %S:
AssertionFormat assertions; see AssertionFormat for %R\n
above options; if undefined, AssertionFormat is Time: %T
used unless assertion causes a breakpoint in Iteration:
which case AssertionFormatBreak is used %D %K: %i
File: %F\n"
AssertionFormatFatal see defines format of messages for VHDL Fatal "** %S:
AssertionFormat assertions; see AssertionFormat for %R\n
above options; if undefined, AssertionFormat is Time: %T
used unless assertion causes a breakpoint in Iteration:
which case AssertionFormatBreak is used %D %K: %i
File: %F\n"
AssertionFormatNote see defines format of messages for VHDL Note "** %S:
AssertionFormat assertions; see AssertionFormat for %R\n
above options; if undefined, AssertionFormat is Time: %T
used unless assertion causes a breakpoint in Iteration:
which case AssertionFormatBreak is used %D%I\n"
CommandHistory any valid sets the name of a file in which to store the commented
filename Main window command history out (;)
DefaultRestartOptions one or more of: sets default behavior for the restart commented
-force, command out (;)
-noassertions,
-nobreakpoint,
-nolist, -nolog,
-nowave
GlobalSharedObjectsList comma seperated loads the specified PLI/FLI shared objects commented
list of filenames with global symbol visibility out (;)
IgnoreError 0,1 if 1, ignore assertion errors; this variable off (0)
can be set interactively with the Tcl set
command (UM-477)
IgnoreNote 0,1 if 1, ignore assertion notes; this variable can off (0)
be set interactively with the Tcl set
command (UM-477)
IgnoreWarning 0,1 if 1, ignore assertion warnings; this variable off (0)
can be set interactively with the Tcl set
command (UM-477)
License any single if set, controls ModelSim license file search all
<license_option> search; license options include: licenses
nomgc - excludes MGC licenses
nomti - excludes MTI licenses
noqueue - do not wait in license queue if no
licenses are available
plus - only use PLUS license
vlog - only use VLOG license
vhdl - only use VHDL license
viewsim - accepts a simulation license
rather than being queued for a viewer
license
Resolution fs, ps, ns, us, ms, simulator resolution; no space between ns
or sec with value and units (i.e., 10fs, not 10 fs);
optional prefix of overridden by the -t argument to vsim (CR-
1, 10, or 100 373); if your delays get truncated, set the
resolution smaller; this value must be less
than or equal to the UserTimeUnit
(described below)
RunLength positive integer default simulation length in units specified 100
by the UserTimeUnit variable; this variable
can be set interactively with the Tcl set
command (UM-477)
UserTimeUnit fs, ps, ns, us, ms, specifies scaling for the Wave window and default
sec, or default the default time units to use for commands
such as force (CR-180) and run (CR-252);
should generally be set to default, in which
case it takes the value of the Resolution
variable; this variable can be set
interactively with the Tcl set command
(UM-477)
Veriuser one or more valid list of dynamically loadable objects for commented
shared object Verilog PLI/VPI applications; see out (;)
names Appendix D - Verilog PLI / VPI / DPI
WLFSizeLimit 0 - positive WLF file size limit; limits WLF file by size 0
integer of MB (as closely as possible) to the specified
number of megabytes; if both size and time
limits are specified the most restrictive is
used; setting to 0 results in no limit
error list of message changes the severity of the listed message numbers to none
numbers "error"; see "Changing message severity level" (UM-
546) for more information
note list of message changes the severity of the listed message numbers to none
numbers "note"; see "Changing message severity level" (UM-
546) for more information
suppress list of message suppresses the listed message numbers; see none
numbers "Changing message severity level" (UM-546) for more
information
warning list of message changes the severity of the listed message numbers to none
numbers "warning"; see "Changing message severity level"
(UM-546) for more information
Environment variables
You can use environment variables in your initialization files. Use a dollar sign ($) before
the environment variable name. For example:
[Library]
work = $HOME/work_lib
test_lib = ./$TESTNUM/work
...
[vsim]
IgnoreNote = $IGNORE_ASSERTS
IgnoreWarning = $IGNORE_ASSERTS
IgnoreError = 0
IgnoreFailure = 0
There is one environment variable, MODEL_TECH, that you cannot — and should not —
set. MODEL_TECH is a special variable set by Model Technology software. Its value is
the name of the directory from which the VCOM or VLOG compilers or VSIM simulator
was invoked. MODEL_TECH is used by the other Model Technology tools to find the
libraries.
Since the file referred to by the "others" clause may itself contain an "others" clause, you
can use this feature to chain a set of hierarchical INI files for library mappings.
You can disable the creation of the transcript file by using the following ModelSim
command immediately after ModelSim starts:
transcript file ""
The line shown above instructs ModelSim to execute the commands in the macro file
named mystartup.do.
; VSIM Startup command
Startup = run -all
The line shown above instructs VSIM to run until there are no events scheduled.
See the do command (CR-151) for additional information on creating do files.
These variables can also be set interactively using the Tcl set command (UM-477). This
capability provides an answer to a common question about disabling warnings at time 0.
You might enter commands like the following in a DO file or at the ModelSim prompt:
set NumericStdNoWarnings 1
run 0
set NumericStdNoWarnings 0
run -all
Alternatively, you could use the when command (CR-407) to accomplish the same thing:
when {$now = @1ns } {set NumericStdNoWarnings 1}
run -all
Note that the time unit (ns in this case) would vary depending on your simulation
resolution.
where <options> can be one or more of -force, -nobreakpoint, -nolist, -nolog, and -nowave.
Example: DefaultRestartOptions = -nolog -force
Note: You can also set these defaults in the modelsim.tcl file. The Tcl file settings will override
the .ini file settings.
VHDL standard
You can specify which version of the 1076 Std ModelSim follows by default using the
VHDL93 variable:
[vcom]
; VHDL93 variable selects language version as the default.
; Default is VHDL-2002.
; Value of 0 or 1987 for VHDL-1987.
; Value of 1 or 1993 for VHDL-1993.
; Default or value of 2 or 2002 for VHDL-2002.
VHDL93 = 2002
Variable precedence
Note that some variables can be set in a .tcl file or a .ini file. A variable set in a .tcl file takes
precedence over the same variable set in a .ini file. For example, assume you have the
following line in your modelsim.ini file:
TranscriptFile = transcript
And assume you have the following line in your modelsim.tcl file:
set PrefMain(file) {}
In this case the setting in the modelsim.tcl file will override that in the modelsim.ini file, and
a transcript file will not be produced.
Variable Result
argc returns the total number of parameters passed to the current macro
Now always returns the current simulation time with time units (e.g.,
110,000 ns) Note: will return a comma between thousands
now when time resolution is a unary unit (i.e., 1ns, 1ps, 1fs): returns the
current simulation time without time units (e.g., 100000)
when time resolution is a multiple of the unary unit (i.e., 10ns,
100ps, 10fs): returns the current simulation time with time units
(e.g. 110000 ns) Note: will not return comma between thousands
Depending on the current simulator state, this command could result in:
The time is 12390 ps 10ps.
If you do not want the dollar sign to denote a simulator variable, precede it with a "\". For
example, \$now will not be interpreted as the current simulator time.
See "ModelSim Tcl time commands" (UM-481) for details on 64-bit time operators.
This appendix documents various status and warning messages that are produced by
ModelSim.
Message format
The format for the messages is:
** <SEVERITY LEVEL>: ([<Tool>[-<Group>]]-<MsgNum>) <Message>
Tool indicates which ModelSim tool was being executed when the message was generated.
For example tool could be vcom, vdel, vsim, etc.
Group indicates the topic to which the problem is related. For example group could be FLI,
PLI, VCD, etc.
Example
# ** Error: (vsim-PLI-3071) ./src/19/testfile(77): $fdumplimit : Too few
arguments.
There are two ways to modify the severity of or suppress notes, warnings, and errors:
• Use the -error, -note, -suppress, and -warning arguments to sccom (CR-254), vcom (CR-
311), vlog (CR-358), or vsim (CR-373). See the command descriptions in the ModelSim
Command Reference for details on those arguments.
• Set a permanent default in the [msg_system] section of the modelsim.ini file. See
"Preference variables located in INI files" (UM-524) for more information.
Exit codes
The table below describes exit codes used by ModelSim tools.
4 Licensing problem
16 Version incompatibility
42 Lost license
43 License read/write failure
Miscellaneous messages
This section describes miscellaneous messages which may be associated with ModelSim.
Message text
# ** Fatal: (vsim-3740) Can't locate a C compiler for compilation of DPI
export tasks/functions.
Meaning
ModelSim was unable to locate a C compiler to compile the DPI exported tasks or functions
in your design.
Suggested action
Make sure that a C compiler is visible from where you are running the simulation.
Message text
# ** WARNING: [8] <path/file_name>:
empty port name in port list.
Meaning
ModelSim reports these warnings if you use the -lint argument to vlog (CR-358). It reports
the warning for any NULL module ports.
Suggested action
If you wish to ignore this warning, do not use the -lint argument.
Lock message
Message text
waiting for lock by user@user. Lockfile is <library_path>/_lock
Meaning
The _lock file is created in a library when you begin a compilation into that library, and it
is removed when the compilation completes. This prevents simultaneous updates to the
library. If a previous compile did not terminate properly, ModelSim may fail to remove the
_lock file.
Suggested action
Manually remove the _lock file after making sure that no one else is actually using that
library.
Message text
Warning: NUMERIC_STD.">": metavalue detected, returning FALSE
Meaning
This warning is an assertion being issued by the IEEE numeric_std package. It indicates
that there is an 'X' in the comparison.
Suggested action
The message does not indicate which comparison is reporting the problem since the
assertion is coming from a standard package. To track the problem, note the time the
warning occurs, restart the simulation, and run to one time unit before the noted time. At
this point, start stepping the simulator until the warning appears. The location of the blue
arrow in a Source window will be pointing at the line following the line with the
comparison.
These messages can be turned off by setting the NumericStdNoWarnings variable to 1
from the command line or in the modelsim.ini file.
Message text
signal is read by the process but is not in the sensitivity list
Meaning
ModelSim outputs this message when you use the -check_synthesis argument to vcom
(CR-311). It reports the warning for any signal that is read by the process but is not in the
sensitivity list.
Suggested action
There are cases where you may purposely omit signals from the sensitivity list even though
they are read by the process. For example, in a strictly sequential process, you may prefer
to include only the clock and reset in the sensitivity list because it would be a design error
if any other signal triggered the process. In such cases, your only option as of version 5.7
is to not use the -check_synthesis argument.
Message text
Tcl_Init Error 2 : Can't find a usable Init.tcl in the following directories :
./../tcl/tcl8.3 .
Meaning
This message typically occurs when the base file was not included in a Unix installation.
When you install ModelSim, you need to download and install 3 files from the ftp site.
These files are:
• modeltech-base.tar.gz
• modeltech-docs.tar.gz
• modeltech-<platform>.exe.gz
If you install only the <platform> file, you will not get the Tcl files that are located in the
base file.
This message could also occur if the file or directory was deleted or corrupted.
Suggested action
Reinstall ModelSim with all three files.
Message text
# ** Warning (vsim-3017): foo.v(1422): [TFMPC] - Too few port connections.
Expected 2, found 1.
# Region: /foo/tb
Meaning
This warning occurs when an instantiation has fewer port connections than the
corresponding module definition. The warning doesn’t necessarily mean anything is
wrong; it is legal in Verilog to have an instantiation that doesn’t connect all of the pins.
However, someone that expects all pins to be connected would like to see such a warning.
Here are some examples of legal instantiations that will and will not cause the warning
message.
Module definition:
module foo (a, b, c, d);
Instantiation that does not connect all pins but will not produce the warning:
foo inst1(e, f, g, ); – positional association
foo inst1(.a(e), .b(f), .c(g), .d()); – named association
Instantiation that does not connect all pins but will produce the warning:
foo inst1(e, f, g); – positional association
foo inst1(.a(e), .b(f), .c(g)); – named association
Any instantiation above will leave pin d unconnected but the first example has a
placeholder for the connection. Here’s another example:
foo inst1(e, , g, h);
Suggested actions
• Check that there is not an extra comma at the end of the port list. (e.g., model(a,b,) ). The
extra comma is legal Verilog and implies that there is a third port connection that is
unnamed.
• If you are purposefully leaving pins unconnected, you can disable these messages using
the +nowarnTFMPC argument to vsim.
Message text
Console output:
Signal 0 caught... Closing vsim vlm child.
vsim is exiting with code 4
FATAL ERROR in license manager
transcript/vsim output:
# ** Error: VSIM license lost; attempting to re-establish.
# Time: 5027 ns Iteration: 2
# ** Fatal: Unable to kill and restart license process.
# Time: 5027 ns Iteration: 2
Meaning
ModelSim queries the license server for a license at regular intervals. Usually these
"License Lost" error messages indicate that network traffic is high, and communication
with the license server times out.
Suggested action
Anything you can do to improve network communication with the license server will
probably solve or decrease the frequency of this problem.
Message text
** Error: Failed to find LMC Smartmodel libswift entry in project file.
# Fatal: Foreign module requested halt
Meaning
ModelSim could not locate the libswift entry and therefore could not link to the Logic
Modeling library.
Suggested action
Uncomment the appropriate libswift entry in the [lmc] section of the modelsim.ini or
project .mpf file. See "VHDL SmartModel interface" (UM-618) for more information.
Message text
# ** Error: (vsim-3197) Load of "/home/cmg/newport2_systemc/chip/vhdl/work/
systemc.so" failed: ld.so.1:
/home/cmg/newport2_systemc/chip/vhdl/work/systemc.so: symbol
_Z28host_respond_to_vhdl_requestPm:
Meaning
The causes for such an error could be:
• missing symbol definition
• bad link order specified in sccom -link
• multiply defined symbols (see "Multiple symbol definitions" (UM-186)
Suggested action
• If the undefined symbol is a C function in your code or a library you are linking with, be
sure that you declared it as an extern "C" function:
extern "C" void myFunc();
• The order in which you place the -link option within the sccom -link command is critical.
Make sure you have used it appropriately. See sccom (CR-254) for syntax and usage
information. See "Misplaced "-link" option" (UM-185) for further explanation of error and
correction.
Message text
work/sc/gensrc/test_ringbuf.o: In function
`test_ringbuf::clock_generator(void)':
Meaning
The most common type of error found during sccom -link operation is the multiple symbol
definition error. This typically arises when the same global symbol is present in more than
one .o file. Several causes are likely:
• A common cause of multiple symbol definitions involves incorrect definition of symbols
in header files. If you have an out-of-line function (one that isn’t preceded by the "inline"
keyword) or a variable defined (i.e., not just referenced or prototyped, but truly defined)
in a .h file, you can't include that .h file in more than one .cpp file.
• Another cause of errors is due to ModelSim’s name association feature. The name
association feature automatically generates .cpp files in the work library. These files
"include" your header files. Thus, while it might appear as though you have included
your header file in only one .cpp file, from the linker’s point of view, it is included in
multiple .cpp files.
Suggested action
Make sure you don’t have any out-of-line functions. Use the "inline" keyword. See
"Multiple symbol definitions" (UM-186).
Introduction
This appendix describes the ModelSim implementation of the Verilog PLI (Programming
Language Interface), VPI (Verilog Procedural Interface) and SystemVerilog DPI (Direct
Programming Interface). These three interfaces provide a mechanism for defining tasks and
functions that communicate with the simulator through a C procedural interface. There are
many third party applications available that interface to Verilog simulators through the PLI
(see "Third party PLI applications" (UM-589)). In addition, you may write your own PLI/
VPI/DPI applications.
ModelSim Verilog implements the PLI as defined in the IEEE Std 1364, with the exception
of the acc_handle_datapath() routine. We did not implement the acc_handle_datapath()
routine because the information it returns is more appropriate for a static timing analysis
tool.
The VPI is partially implemented as defined in the IEEE Std 1364-2001. The list of
currently supported functionality can be found in the following file:
<install_dir>/modeltech/docs/technotes/Verilog_VPI.note
The various callback functions (checktf, sizetf, calltf, and misctf) are described in detail in
the IEEE Std 1364. The simulator calls these functions for various reasons. All callback
functions are optional, but most applications contain at least the calltf function, which is
called when the system task or function is executed in the Verilog code. The first argument
to the callback functions is the value supplied in the data field (many PLI applications don't
use this field). The type field defines the entry as either a system task (USERTASK) or a
system function that returns either a register (USERFUNCTION) or a real
(USERREALFUNCTION). The tfname field is the system task or function name (it must
begin with $). The remaining fields are not used by ModelSim Verilog.
On loading of a PLI application, the simulator first looks for an init_usertfs function, and
then a veriusertfs array. If init_usertfs is found, the simulator calls that function so that it
can call mti_RegisterUserTF() for each system task or function defined. The
mti_RegisterUserTF() function is declared in veriuser.h as follows:
void mti_RegisterUserTF(p_tfcell usertf);
The storage for each usertf entry passed to the simulator must persist throughout the
simulation because the simulator de-references the usertf pointer to call the callback
functions. We recommend that you define your entries in an array, with the last entry set to
0. If the array is named veriusertfs (as is the case for linking to Verilog-XL), then you don't
have to provide an init_usertfs function, and the simulator will automatically register the
entries directly from the array (the last entry must be 0). For example,
s_tfcell veriusertfs[] = {
{usertask, 0, 0, 0, abc_calltf, 0, "$abc"},
{usertask, 0, 0, 0, xyz_calltf, 0, "$xyz"},
{0} /* last entry must be 0 */
};
Alternatively, you can add an init_usertfs function to explicitly register each entry from the
array:
void init_usertfs()
{
p_tfcell usertf = veriusertfs;
while (usertf->type)
mti_RegisterUserTF(usertf++);
}
It is an error if a PLI shared library does not contain a veriusertfs array or an init_usertfs
function.
Since PLI applications are dynamically loaded by the simulator, you must specify which
applications to load (each application must be a dynamically loadable library, see
"Compiling and linking C applications for PLI/VPI/DPI" (UM-568)). The PLI applications
are specified as follows (note that on a Windows platform the file extension would be .dll):
• As a list in the Veriuser entry in the modelsim.ini file:
Veriuser = pliapp1.so pliapp2.so pliappn.so
The various methods of specifying PLI applications can be used simultaneously. The
libraries are loaded in the order listed above. Environment variable references can be used
in the paths to the libraries in all cases.
Example
PLI_INT32 MyFuncCalltf( PLI_BYTE8 *user_data )
{ ... }
PLI_INT32 MyFuncCompiletf( PLI_BYTE8 *user_data )
{ ... }
PLI_INT32 MyFuncSizetf( PLI_BYTE8 *user_data )
{ ... }
PLI_INT32 MyEndOfCompCB( p_cb_data cb_data_p )
{ ... }
PLI_INT32 MyStartOfSimCB( p_cb_data cb_data_p )
{ ... }
void RegisterMySystfs( void )
{
vpiHandle tmpH;
s_cb_data callback;
s_vpi_systf_data systf_data;
systf_data.type = vpiSysFunc;
systf_data.sysfunctype = vpiSizedFunc;
systf_data.tfname = "$myfunc";
systf_data.calltf = MyFuncCalltf;
systf_data.compiletf = MyFuncCompiletf;
systf_data.sizetf = MyFuncSizetf;
systf_data.user_data = 0;
tmpH = vpi_register_systf( &systf_data );
vpi_free_object(tmpH);
callback.reason = cbEndOfCompile;
callback.cb_rtn = MyEndOfCompCB;
callback.user_data = 0;
tmpH = vpi_register_cb( &callback );
vpi_free_object(tmpH);
callback.reason = cbStartOfSimulation;
callback.cb_rtn = MyStartOfSimCB;
callback.user_data = 0;
tmpH = vpi_register_cb( &callback );
vpi_free_object(tmpH);
}
void (*vlog_startup_routines[ ] ) () = {
RegisterMySystfs,
0 /* last entry must be 0 */
};
Loading VPI applications into the simulator is the same as described in "Registering DPI
applications" (UM-565).
Your code must provide imported functions or tasks, compiled with an external compiler.
An imported task must return an int value, "1" indicating that it is returning due to a disable,
or "0" indicating otherwise.
These imported functions or objects may then be loaded as a shared library into the
simulator with either the command line option -sv_lib <lib> or -sv_liblist
<bootstrap_file>. For example,
vlog dut.v
gcc -shared -o imports.so imports.c
vsim -sv_lib imports top -do <do_file>
The -sv_lib option specifies the shared library name, without an extension. A file extension
is added by the tool, as appropriate to your platform. For a list of file extensions accepted
by platform, see "DPI file loading" (UM-580).
You can also use the command line options -sv_root and -sv_liblist to control the process
for loading imported functions and tasks. These options are defined in the SystemVerilog
3.1a LRM.
dpiheader.h
Step 2 Include header
#include "dpiheader.h"
Step 1.5 Windows only
vsim .c
vsim -dpiexportobj exportobj.o
gcc
exportobj.o C compiler
mtipli.lib
.o
compiled
user code
ld/link
loader/linker Step 3
Compile
and load/link
C code
<test>.so
shared object
Step 4 Simulate
vsim
vsim -sv_lib <test>
Steps in flow
Windows platforms
For the Verilog PLI, the <init_function> should be "init_usertfs". Alternatively, if there is
no init_usertfs function, the <init_function> specified on the command line should be
"veriusertfs". For the Verilog VPI, the <init_function> should be "vlog_startup_routines".
These requirements ensure that the appropriate symbol is exported, and thus ModelSim can
find the symbol when it dynamically loads the DLL.
When executing cl commands in a DO file, use the /NOLOGO switch to prevent the
Microsoft C compiler from writing the logo banner to stderr. Writing the logo causes Tcl
to think an error occurred.
If you need to run the profiler (see Chapter 12 - Profiling performance and memory use)
on a design that contains PLI/VPI code, add these two switches to the link commands
shown above:
/DEBUG /DEBUGTYPE:COFF
These switches add symbols to the .dll that the profiler can use in its report.
ModelSim recommends the use of MinGW gcc compiler rather than the Cygwin gcc
compiler. MinGW gcc is available on the ModelSim FTP site.
The -dpiexportobj generates an object file <objname> that contains "glue" code for
exported tasks and functions. You must add that object file to the link line for your .dll,
listed after the other object files. For example, a link line for MinGW would be:
gcc -shared -o app.dll app.o <objname>
-L<install_dir>\modeltech\win32 -lmtipli
gcc compiler
gcc -c -I/<install_dir>/modeltech/include app.c
When using -Bsymbolic with ld, all symbols are first resolved within the shared library at
link time. This will result in a list of undefined symbols. This is only a warning for shared
libraries and can be ignored. If you are using ModelSim RedHat version 6.0 through 7.1,
you also need to add the -noinhibit-exec switch when you specify -Bsymbolic.
The compiler switch -freg-struct-return must be used when compiling any FLI application
code that contains foreign functions that return real or time values.
The -m64 and -m elf_x86_64 switches are required to compile for 64-bit operation. To
compile for 32-bit operation, use the -m32 argument instead of -m64 at the gcc command
line. These arguments for 32-bit or 64-bit operation are required only if the desired
operation differs from the default gcc settings.
If your PLI/VPI/DPI application requires a user or vendor-supplied C library, or an
additional system library, you will need to specify that library when you link your PLI/VPI/
DPI application. For example, to use the system math library libm, specify -lm to the ld
command:
gcc -m64 -c -fPIC -I/<install_dir>/modeltech/include math_app.c
ld -m elf_x86_64 -shared -Bsymbolic -E --allow-shlib-undefined \
-o math_app.so math_app.o -lm
gcc compiler
gcc -c -I/<install_dir>/modeltech/include app.c
ld -G -Bsymbolic -o app.so app.o -lc
cc compiler
cc -c -I/<install_dir>/modeltech/include app.c
ld -G -Bsymbolic -o app.so app.o -lc
When using -Bsymbolic with ld, all symbols are first resolved within the shared library at
link time. This will result in a list of undefined symbols. This is only a warning for shared
libraries and can be ignored.
gcc compiler
gcc -c -I<install_dir>/modeltech/include -m64 -fPIC app.c
gcc -shared -o app.so -m64 app.o
This was tested with gcc 3.2.2. You may need to add the location of libgcc_s.so.1 to the
LD_LIBRARY_PATH environment variable.
cc compiler
cc -v -xarch=v9 -O -I<install_dir>/modeltech/include -c app.c
ld -G -Bsymbolic app.o -o app.so
When using -Bsymbolic with ld, all symbols are first resolved within the shared library at
link time. This will result in a list of undefined symbols. This is only a warning for shared
libraries and can be ignored.
gcc compiler
gcc -c -fPIC -I/<install_dir>/modeltech/include app.c
ld -b -o app.sl app.o -lc
cc compiler
cc -c +z +DD32 -I/<install_dir>/modeltech/include app.c
ld -b -o app.sl app.o -lc
Note that -fPIC may not work with all versions of gcc.
64-bit HP platform
cc compiler
cc -v +DD64 -O -I<install_dir>/modeltech/include -c app.c
ld -b -o app.sl app.o -lc
gcc compiler
gcc -c -I/<install_dir>/modeltech/include app.c
ld -o app.sl app.o -bE:app.exp \
-bI:/<install_dir>/modeltech/rs6000/mti_exports -bM:SRE -bnoentry -lc
cc compiler
cc -c -I/<install_dir>/modeltech/include app.c
ld -o app.sl app.o -bE:app.exp \
-bI:/<install_dir>/modeltech/rs6000/mti_exports -bM:SRE -bnoentry -lc
The app.exp file must export the PLI/VPI initialization function or table. For the PLI, the
exported symbol should be "init_usertfs". Alternatively, if there is no init_usertfs function,
then the exported symbol should be "veriusertfs". For the VPI, the exported symbol should
be "vlog_startup_routines". These requirements ensure that the appropriate symbol is
exported, and thus ModelSim can find the symbol when it dynamically loads the shared
object.
When using AIX 4.3 in 32-bit mode, you must add the -DUSE_INTTYPES switch to the
compile command lines. This switch prevents a name conflict that occurs between
inttypes.h and mti.h.
The -dpiexportobj generates the object file <objname> that contains "glue" code for
exported tasks and functions. You must add that object file to the link line, listed after the
other object files. For example, a link line would be:
ld -o app.so app.o <objname>
-bE:<isymfile> -bI:/<install_dir>/modeltech/rs6000/mti_exports -bM:SRE
-bnoentry -lc
VisualAge cc compiler
cc -c -q64 -I/<install_dir>/modeltech/include app.c
ld -o app.s1 app.o -b64 -bE:app.exports \
-bI:/<install_dir>/modeltech/rs64/mti_exports -bM:SRE -bnoentry -lc
The -dpiexportobj generates the object file <objname> that contains "glue" code for
exported tasks and functions. You must add that object file to the link line, listed after the
other object files. For example, a link line would be:
ld -o app.dll app.o <objname>
-bE:<isymfile> -bI:/<install_dir>/modeltech/rs6000/mti_exports -bM:SRE
-bnoentry -lc
The header files veriuser.h, acc_user.h, and vpi_user.h, svdpi.h already include this type of
extern. You must also put the PLI/VPI/DPI shared library entry point (veriusertfs,
init_usertfs, or vlog_startup_routines) inside of this type of extern.
The following platform-specific instructions show you how to compile and link your
PLI/VPI/DPI C++ applications so that they can be loaded by ModelSim.
Although compilation and simulation switches are platform-specific, loading shared
libraries is the same for all platforms. For information on loading libraries, see "DPI file
loading" (UM-580).
Windows platforms
If you need to run the profiler (see Chapter 12 - Profiling performance and memory use)
on a design that contains PLI/VPI code, add these two switches to the link command shown
above:
/DEBUG /DEBUGTYPE:COFF
These switches add symbols to the .dll that the profiler can use in its report.
ModelSim recommends the use of MinGW gcc compiler rather than the Cygwin gcc
compiler. MinGW gcc is available on the ModelSim FTP site.
The -dpiexportobj generates the object file <objname> that contains "glue" code for
exported tasks and functions. You must add that object file to the link line, listed after the
other object files. For example, if the object name was dpi1, the link line for MinGW would
be:
g++ -shared -o app.dll app.o <objname>
-L<install_dir>\modeltech\win32 -lmtipli
The -m64 and -m elf_x86_64 switches are required to compile for 64-bit operation. To
compile for 32-bit operation, use the -m32 argument instead of -m64 at the gcc command
line. These arguments for 32-bit or 64-bit operation are required only if the desired
operation differs from the default gcc settings.
If your PLI/VPI/DPI application requires a user or vendor-supplied C library, or an
additional system library, you will need to specify that library when you link your PLI/VPI/
DPI application. For example, to use the system math library libm, specify -lm to the ld
command:
g++ -c -fPIC -I/<install_dir>/modeltech/include math_app.cpp
ld -shared -Bsymbolic -E --allow-shlib-undefined -o math_app.so math_app.o -lm
When using -Bsymbolic with ld, all symbols are first resolved within the shared library at
link time. This will result in a list of undefined symbols. This is only a warning for shared
libraries and can be ignored.
This was tested with gcc 3.2.2. You may need to add the location of libgcc_s.so.1 to the
LD_LIBRARY_PATH environment variable.
cc compiler
cc -v -xarch=v9 -O -I<install_dir>/modeltech/include -c app.cpp
ld -G -Bsymbolic app.o -o app.so
When using -Bsymbolic with ld, all symbols are first resolved within the shared library at
link time. This will result in a list of undefined symbols. This is only a warning for shared
libraries and can be ignored.
cc compiler
cc -c +z +DD32 -I/<install_dir>/modeltech/include app.cpp
ld -b -o app.sl app.o -lc
Note that -fPIC may not work with all versions of gcc.
64-bit HP platform
cc compiler
cc -v +DD64 -O -I<install_dir>/modeltech/include -c app.cpp
ld -b -o app.sl app.o -lc
The app.exp file must export the PLI/VPI initialization function or table. For the PLI, the
exported symbol should be "init_usertfs". Alternatively, if there is no init_usertfs function,
then the exported symbol should be "veriusertfs". For the VPI, the exported symbol should
be "vlog_startup_routines". These requirements ensure that the appropriate symbol is
exported, and thus ModelSim can find the symbol when it dynamically loads the shared
object.
When using AIX 4.3 in 32-bit mode, you must add the -DUSE_INTTYPES switch to the
compile command lines. This switch prevents a name conflict that occurs between
inttypes.h and mti.h.
The -dpiexportobj generates the object file <objname> that contains "glue" code for
exported tasks and functions. You must add that object file to the link line, listed after the
other object files. For example, a link line would be:
ld -o app.dll app.o <objname>
-bE:<isymfile> -bI:/<install_dir>/modeltech/rs6000/mti_exports -bM:SRE
-bnoentry -lc
The -dpiexportobj generates the object file <objname> that contains "glue" code for
exported tasks and functions. You must add that object file to the link line, listed after the
other object files. For example, a link line would be:
ld -o app.so app.o <objname>
-bE:<isymfile> -bI:/<install_dir>/modeltech/rs6000/mti_exports -bM:SRE
-bnoentry -lc
Note: On Windows platforms, the file names shown above should end with .dll rather
than .so.
The various methods of specifying PLI/VPI applications can be used simultaneously. The
libraries are loaded in the order listed above. Environment variable references can be used
in the paths to the libraries in all cases.
See also Appendix B - ModelSim variables for more information on the modelsim.ini file.
-sv_root <name> specifies a new prefix for shared objects as specified by -sv_lib
When the simulator finds an imported task or function, it searches for the symbol in the
collection of shared objects specified using these arguments.
For example, you can specify the DPI application as follows:
vsim -sv_lib dpiapp1 -sv_lib dpiapp2 -sv_lib dpiappn
It is a mistake to specify DPI import tasks and functions (tf) inside PLI/VPI shared objects.
However, a DPI import tf can make calls to PLI/VPI C code, providing that vsim -gblso
was used to mark the PLI/VPI shared object with global symbol visibility. See "Loading
shared objects with global symbol visibility" (UM-581).
The -gblso argument works in conjunction with the GlobalSharedObjectList variable in the
modelsim.ini file. This variable allows user C code in other shared objects to refer to
symbols in a shared object that has been marked as global. All shared objects marked as
global are loaded by the simulator earlier than any non-global shared objects.
PLI example
The following example is a trivial, but complete PLI application.
hello.c:
#include "veriuser.h"
static PLI_INT32 hello()
{
io_printf("Hi there\n");
return 0;
}
s_tfcell veriusertfs[] = {
{usertask, 0, 0, 0, hello, 0, "$hello"},
{0} /* last entry must be 0 */
};
hello.v:
module hello;
initial $hello;
endmodule
% cc -c -I<install_dir>/modeltech/include hello.c
% ld -G -o hello.sl hello.o
% vlib work
% vlog hello.v
VPI example
The following example is a trivial, but complete VPI application. A general VPI example
can be found in <install_dir>/modeltech/examples/vpi.
hello.c:
#include "vpi_user.h"
static PLI_INT32 hello(PLI_BYTE8 * param)
{
vpi_printf( "Hello world!\n" );
return 0;
}
void (*vlog_startup_routines[])() = {
RegisterMyTfs,
0
};
hello.v:
module hello;
initial $hello;
endmodule
% vlib work
% vlog hello.v
DPI example
The following example is a trivial, but complete DPI application. For win32 and RS6000
platforms, one additional step is required along with some new arguments. For the latest
detailed instructions for compiling and simulating DPI imported and exported tasks and
functions, see the modeltech/examples/dpi directory. There you will find examples with a
subdirectory for each platform that contains the platform specific commands and
arguments.
hello_c.c:
#include "svdpi.h"
#include "dpiheader.h"
int c_task(int i, int *o)
{
printf("Hello from c_task()\n");
verilog_task(i, o); /* Call back into Verilog */
*o = i;
return(0); /* Return success (required by tasks) */
}
hello.v:
module hello_top;
int ret;
export "DPI" task verilog_task;
task verilog_task(input int i, output int o);
#10;
$display("Hello from verilog_task()");
endtask
import "DPI" context task c_task(input int i, output int o);
initial
begin
c_task(1, ret); // Call the c task named 'c_task()'
end
endmodule
% vlib work
% vlog -sv -dpiheader dpiheader.h hello.v
reason_synch
For the end of time step event scheduled by tf_synchronize().
reason_rosynch
For the end of time step event scheduled by tf_rosynchronize().
reason_reactivate
For the simulation event scheduled by tf_setdelay().
reason_paramdrc
Not supported in ModelSim Verilog.
reason_force
Not supported in ModelSim Verilog.
reason_release
Not supported in ModelSim Verilog.
reason_disable
Not supported in ModelSim Verilog.
If your PLI application uses these types of objects, then it is important to call acc_close()
to free the memory allocated for these objects when the application is done using them.
If your PLI application places value change callbacks on accRegBit or accTerminal objects,
do not call acc_close() while these callbacks are in effect.
The PLI application is now ready to be run with ModelSim Verilog. All that's left is to
specify the resulting object file to the simulator for loading using the Veriuser entry in the
modesim.ini file, the -pli simulator argument, or the PLIOBJS environment variable (see
"Registering DPI applications" (UM-565)).
Note: On the HP700 platform, the object files must be compiled as position-independent
code by using the +z compiler argument. Since, the object files supplied for Verilog-XL
may be compiled for static linking, you may not be able to use the object files to create
a dynamically loadable object for ModelSim Verilog. In this case, you must get the third
party application vendor to supply the object files compiled as position-independent
code.
The type and fulltype constants for VHDL objects are defined in the acc_vhdl.h include
file. All of these objects (except signals) are scope objects that define levels of hierarchy in
the structure window. Currently, the PLI ACC interface has no provision for obtaining
handles to generics, types, constants, variables, attributes, subprograms, and processes.
However, some of these objects can be manipulated through the ModelSim VHDL foreign
interface (mti_* routines). See the FLI Reference Manual for more information.
tf_isizep tf_subtract_long
svPutUserData
svGetUserData
svGetCallerInfosv
IsDisabledState
svAckDisabledState
A call to this routine flushes the VCD file buffer (same effect as calling $dumpflush in the
Verilog code).
int tf_getlongsimtime(int *aof_hightime)
This routine gets the current simulation time as a 64-bit integer. The low-order bits are
returned by the routine, while the high-order bits are stored in the aof_hightime argument.
PLI/VPI tracing
The foreign interface tracing feature is available for tracing PLI and VPI function calls.
Foreign interface tracing creates two kinds of traces: a human-readable log of what
functions were called, the value of the arguments, and the results returned; and a set of
C-language files that can be used to replay what the foreign interface code did.
Invoking a trace
To invoke the trace, call vsim (CR-373) with the -trace_foreign argument:
Syntax
vsim
-trace_foreign <action> [-tag <name>]
Arguments
<action>
Specifies one of the following actions:
-tag <name>
Used to give distinct file names for multiple traces. Optional.
Examples
vsim -trace_foreign 1 mydesign
Creates a logfile.
vsim -trace_foreign 3 mydesign
Creates both a logfile and a set of replay files.
vsim -trace_foreign 1 -tag 2 mydesign
Creates a logfile with a tag of "2".
The tracing operations will provide tracing during all user foreign code-calls, including
PLI/VPI user tasks and functions (calltf, checktf, sizetf and misctf routines), and Verilog
VCL callbacks.
1 Compile the application code with debugging information (using the -g option) and
without optimizations (for example, don’t use the -O option).
On Solaris, AIX, and Linux systems you can use either gdb or ddd. On HP-UX systems
you can use the wdb debugger from HP. You will need version 1.2 or later.
4 In some debuggers, you must use the share command to load the application's symbols.
At this point all of the application's symbols should be visible. You can now set breakpoints
in and single step through your application code.
E - ModelSim shortcuts
Appendix contents
Command shortcuts . . . . . . . . . . . . . UM-603
Command history shortcuts . . . . . . . . . . . UM-603
This appendix is a collection of the keyboard and command shortcuts available in the
ModelSim GUI.
Command shortcuts
• You may abbreviate command syntax, but there’s a catch — the minimum number of
characters required to execute a command are those that make it unique. Remember, as
we add new commands some of the old shortcuts may not work. For this reason
ModelSim does not allow command name abbreviations in macro files. This minimizes
your need to update macro files as new commands are added.
• Multiple commands may be entered on one line if they are separated by semi-colons (;).
For example:
ModelSim> vlog -nodebug=ports level3.v level2.v ; vlog -nodebug top.v
The return value of the last function executed is the only one printed to the transcript.
This may cause some unexpected behavior in certain circumstances. Consider this
example:
vsim -c -do "run 20 ; simstats ; quit -f" top
You probably expect the simstats results to display in the Transcript window, but they
will not, because the last command is quit -f. To see the return values of intermediate
commands, you must explicitly print the results. For example:
vsim -do "run 20 ; echo [simstats]; quit -f" -c top
Shortcut Description
!! repeats the last command
Shortcut Description
!n repeats command number n; n is the VSIM prompt number (e.g.,
for this prompt: VSIM 12>, n =12)
!abc repeats the most recent command starting with "abc"
^xyz^ab^ replaces "xyz" in the last command with "ab"
up and down arrows scrolls through the command history with the keyboard arrows
< left-button - click > on previous ModelSim or VSIM prompt copy and paste previous command
string to current prompt
< left | right arrow > move cursor left | right one character
< control > < left | right arrow > move cursor left | right one word
< shift > < left | right | up | down arrow > extend selection of text
< control > < shift > < left | right arrow > extend selection of text by word
< up | down arrow > scroll through command history (in Source
window, moves cursor one line up | down)
< control > < up | down > moves cursor up | down one paragraph
< control > < home > move cursor to the beginning of the text
< control > < end > move cursor to the end of the text
< backspace >, < control-h > < backspace > delete character to the left
< delete >, < control-d > < delete > delete character to the right
< control - f > <right arrow> move cursor right one character
< control - n > move cursor one line down (Source window
only under Windows)
< control - p > move cursor one line up (Source window only
under Windows)
< control - t > reverse the order of the two characters on either
side of the cursor
< control - x >, < control - s> < control - s > save
< control - y >, F18 < control - v > paste the selection
none < control - a > select the entire contents of the widget
< control - ->, < control - / > < control - Z > undoes previous edits in the Source window
< meta - "<" > none move cursor to the beginning of the file
< meta - ">" > none move cursor to the end of the file
< meta - v >, PageUp PageUp move cursor up one screen
The Main window allows insertions or pastes only after the prompt; therefore, you don’t
need to set the cursor when copying strings to the command line.
Key Action
<left arrow> scroll listing left (selects and highlights the item to the left of the
currently selected item)
<right arrow> scroll listing right (selects and highlights the item to the right of
the currently selected item)
<control-f> Windows opens the Find dialog box to find the specified item label within
<control-s> UNIX the list display
< control - left-button - drag down and right>a zoom area (in)
< control - left-button - click on a scroll arrow > scrolls window to very top or
bottom (vertical scroll) or far left or
right (horizontal scroll)
< middle mouse-button - click in scroll bar trough> scrolls window to position of click
(UNIX) only
a. If you enter zoom mode by selecting View > Mouse Mode > Zoom Mode, you do
not need to hold down the <Ctrl> key.
Keystroke Action
<up arrow>/ with mouse over waveform pane, scrolls entire window up/
<down arrow> down one line; with mouse over pathname or values pane,
scrolls highlight up/down one line
Keystroke Action
<control-f> Windows open the find dialog box; searches within the specified field in
<control-s> UNIX the pathname pane for text strings
F - System initialization
Appendix contents
Files accessed during startup . . . . . . . . . . . UM-612
Environment variables accessed during startup . . . . . . UM-613
ModelSim goes through numerous steps as it initializes the system during startup. It
accesses various files and environment variables to determine library mappings, configure
the GUI, check licensing, and so forth.
File Purpose
location map file used by ModelSim tools to find source files based on easily
reallocated "soft" paths; default file name is mgc_location_map
.modelsim (UNIX) or contains last working directory, project file, printer defaults, and
Windows registry window and toolbar configurations
Initialization sequence
The following list describes in detail ModelSim’s initialization sequence. The sequence
includes a number of conditional structures, the results of which are determined by the
existence of certain files and the current settings of environment variables.
In the steps below, names in uppercase denote environment variables (except
MTI_LIB_DIR which is a Tcl variable). Instances of $(NAME) denote paths that are
determined by an environment variable (except $(MTI_LIB_DIR) which is determined by
a Tcl variable).
4 Reads various variables from the [vsim] section of the modelsim.ini file. See "[vsim]
simulator control variables" (UM-529) for more details.
5 Parses any command line arguments that were included when you started ModelSim and
reports any problems.
• set MODEL_TECH_TCL=$(MODEL_TECH)/../tcl
• set TCL_LIBRARY=$(MODEL_TECH_TCL)/tcl8.3
• set TK_LIBRARY=$(MODEL_TECH_TCL)/tk8.3
• set ITCL_LIBRARY=$(MODEL_TECH_TCL)/itcl3.0
• set ITK_LIBRARY=$(MODEL_TECH_TCL)/itk3.0
• set VSIM_LIBRARY=$(MODEL_TECH_TCL)/vsim
8 Checks for a valid license (a license is not checked out unless specified by a modelsim.ini
setting or command line option).
The next four steps relate to initializing the graphical user interface.
10 Loads $(MTI_LIB_DIR)/vsim/pref.tcl.
12 Loads last working directory, project file, printer defaults, and window and toolbar
configurations from the registry (Windows) or $(HOME)/.modelsim (UNIX).
That completes the initialization sequence. Also note the following about the modelsim.ini
file:
• When you change the working directory within ModelSim, the tool reads the [library],
[vcom], and [vlog] sections of the local modelsim.ini file. When you make changes in the
compiler or simulator options dialog or use the vmap command, the tool updates the
appropriate sections of the file.
• The pref.tcl file references the default .ini file via the [GetPrivateProfileString] Tcl
command. The .ini file that is read will be the default file defined at the time pref.tcl is
loaded.
The Logic Modeling SWIFT-based SmartModel library can be used with ModelSim VHDL and
Verilog. The SmartModel library is a collection of behavioral models supplied in binary form
with a procedural interface that is accessed by the simulator. This appendix describes how to
use the SmartModel library with ModelSim.
The SmartModel library must be obtained from Logic Modeling along with the
documentation that describes how to use it. This appendix only describes the specifics of
using the library with ModelSim.
A 32-bit SmartModel will not run with a 64-bit version of SE. When trying to load the
operating system specific 32-bit library into the 64-bit executable, the pointer sizes will be
incorrect.
The libsm entry points to the ModelSim dynamic link library that interfaces the foreign
architecture to the SmartModel software. The libswift entry points to the Logic Modeling
dynamic link library software that accesses the SmartModels. The simulator automatically
loads both the libsm and libswift libraries when it elaborates a SmartModel foreign
architecture.
By default, the libsm entry points to the libsm.sl supplied in the ModelSim installation
directory indicated by the MODEL_TECH environment variable. ModelSim
automatically sets the MODEL_TECH environment variable to the appropriate directory
containing the executables and binaries for the current operating system.
Syntax
sm_entity
[-] [-xe] [-xa] [-c] [-all] [-v] [-93] [<SmartModelName>...]
Arguments
-
Read SmartModel names from standard input.
-xe
Do not generate entity declarations.
-xa
Do not generate architecture bodies.
-c
Generate component declarations.
-all
Select all models installed in the SmartModel library.
-v
Display progress messages.
-93
Use extended identifiers where needed.
<SmartModelName>
Name of a SmartModel (see the SmartModel library documentation for details on
SmartModel names).
By default, the sm_entity tool writes an entity and foreign architecture to stdout for each
SmartModel name listed on the command line. Optionally, you can include the component
declaration (-c), exclude the entity (-xe), and exclude the architecture (-xa).
The simplest way to prepare SmartModels for use with ModelSim VHDL is to generate the
entities and foreign architectures for all installed SmartModels, and compile them into a
library named lmc. This is easily accomplished with the following commands:
% sm_entity -all > sml.vhd
% vlib lmc
% vcom -work lmc sml.vhd
To instantiate the SmartModels in your VHDL design, you also need to generate
component declarations for the SmartModels. Add these component declarations to a
package named sml (for example), and compile the package into the lmc library:
% sm_entity -all -c -xe -xa > smlcomp.vhd
Edit the resulting smlcomp.vhd file to turn it into a package of SmartModel component
declarations as follows:
library ieee;
use ieee.std_logic_1164.all;
package sml is
<component declarations go here>
end sml;
The SmartModels can now be referenced in your design by adding the following library
and use clauses to your code:
library lmc;
use lmc.sml.all;
The following is an example of an entity and foreign architecture created by sm_entity for
the cy7c285 SmartModel.
library ieee;
use ieee.std_logic_1164.all;
entity cy7c285 is
generic (TimingVersion : STRING := "CY7C285-65";
DelayRange : STRING := "Max";
MemoryFile : STRING := "memory" );
port ( A0 : in std_logic;
A1 : in std_logic;
A2 : in std_logic;
A3 : in std_logic;
A4 : in std_logic;
A5 : in std_logic;
A6 : in std_logic;
A7 : in std_logic;
A8 : in std_logic;
A9 : in std_logic;
A10 : in std_logic;
A11 : in std_logic;
A12 : in std_logic;
A13 : in std_logic;
A14 : in std_logic;
A15 : in std_logic;
CS : in std_logic;
O0 : out std_logic;
O1 : out std_logic;
O2 : out std_logic;
O3 : out std_logic;
O4 : out std_logic;
O5 : out std_logic;
O6 : out std_logic;
O7 : out std_logic;
WAIT_PORT : inout std_logic );
end;
Entity details
• The entity name is the SmartModel name (you can manually change this name if you
like).
• The port names are the same as the SmartModel port names (these names must not be
changed). If the SmartModel port name is not a valid VHDL identifier, then sm_entity
automatically converts it to a valid name. If sm_entity is invoked with the -93 option,
then the identifier is converted to an extended identifier, and the resulting entity must also
be compiled with the -93 option. If the -93 option had been specified in the example
above, then WAIT would have been converted to \WAIT\. Note that in this example the
port WAIT was converted to WAIT_PORT because wait is a VHDL reserved word.
• The port types are std_logic. This data type supports the full range of SmartModel logic
states.
• The DelayRange, TimingVersion, and MemoryFile generics represent the SmartModel
attributes of the same name. Consult your SmartModel library documentation for a
description of these attributes (and others). Sm_entity creates a generic for each attribute
of the particular SmartModel. The default generic value is the default attribute value that
the SmartModel has supplied to sm_entity.
Architecture details
• The first part of the foreign attribute string (sm_init) is the same for all SmartModels.
• The second part ($MODEL_TECH/libsm.sl) is taken from the libsm entry in the
initialization file, modelsim.ini.
• The third part (cy7c285) is the SmartModel name. This name correlates the architecture
with the SmartModel at elaboration.
Vector ports
The entities generated by sm_entity only contain single-bit ports, never vectored ports.
This is necessary because ModelSim correlates entity ports with the SmartModel SWIFT
interface by name. However, for ease of use in component instantiations, you may want to
create a custom component declaration and component specification that groups ports into
vectors. You can also rename and reorder the ports in the component declaration. You can
also reorder the ports in the entity declaration, but you can't rename them!
The following is an example component declaration and specification that groups the
address and data ports of the CY7C285 SmartModel:
component cy7c285
generic ( TimingVersion : STRING := "CY7C285-65";
DelayRange : STRING := "Max";
MemoryFile : STRING := "memory" );
port ( A : in std_logic_vector (15 downto 0);
CS : in std_logic;
O : out std_logic_vector (7 downto 0);
WAIT_PORT : inout std_logic );
end component;
A2 => A(2),
A3 => A(3),
A4 => A(4),
A5 => A(5),
A6 => A(6),
A7 => A(7),
A8 => A(8),
A9 => A(9),
A10 => A(10),
A11 => A(11),
A12 => A(12),
A13 => A(13),
A14 => A(14),
A15 => A(15),
CS => CS,
O0 => O(0),
O1 => O(1),
O2 => O(2),
O3 => O(3),
O4 => O(4),
O5 => O(5),
O6 => O(6),
O7 => O(7),
WAIT_PORT => WAIT_PORT );
Command channel
The command channel is a SmartModel feature that lets you invoke SmartModel specific
commands. These commands are documented in the SmartModel library documentation
from Synopsys. ModelSim provides access to the Command Channel from the command
line. The form of a SmartModel command is:
lmc <instance_name>|-all "<SmartModel command>"
Use -all to apply the command to all SmartModel instances. For example, to turn timing
checks off for all SmartModel instances:
lmc -all "SetConstraints Off"
There are also some SmartModel commands that apply globally to the current simulation
session rather than to models. The form of a SmartModel session command is:
lmcsession "<SmartModel session command>"
SmartModel Windows
Some models in the SmartModel library provide access to internal registers with a feature
called SmartModel Windows. Refer to Logic Modeling’s SmartModel library
documentation (available on Synopsys’ web site) for details on this feature. The simulator
interface to this feature is described below.
Window names that are not valid VHDL or Verilog identifiers are converted to VHDL
extended identifiers. For example, with a window named z1I10.GSR.OR, ModelSim will
treat the name as \z1I10.GSR.OR\ (for all commands including lmcwin, add wave, and
examine). You must then use that name in all commands. For example,
add wave /top/swift_model/\z1I10.GSR.OR\
ReportStatus
The ReportStatus command displays model information, including the names of window
registers. For example,
lmc /top/u1 ReportStatus
This model contains window registers named wa, wb, and wc. These names can be used in
subsequent window (lmcwin) commands.
lmcwin read
The lmcwin read command displays the current value of a window. The optional radix
argument is -binary, -decimal, or -hexadecimal (these names can be abbreviated). The
default is to display the value using the std_logic characters. For example, the following
command displays the 64-bit window wc in hexadecimal:
lmcwin read /top/u1/wc -h
lmcwin write
The lmcwin write command writes a value into a window. The format of the value
argument is the same as used in other simulator commands that take value arguments. For
example, to write 1 to window wb, and all 1’s to window wc:
lmcwin write /top/u1/wb 1
lmcwin write /top/u1/wc X"FFFFFFFFFFFFFFFF"
lmcwin enable
The lmcwin enable command enables continuous monitoring of a window. The specified
window is added to the model instance as a signal (with the same name as the window) of
type std_logic or std_logic_vector. This signal's values can then be referenced in simulator
commands that read signal values, such as the add list command (CR-48) shown below. The
window signal is continuously updated to reflect the value in the model. For example, to
list window wa:
lmcwin enable /top/u1/wa
add list /top/u1/wa
lmcwin disable
The lmcwin disable command disables continuous monitoring of a window. The window
signal is not deleted, but it no longer is updated when the model’s window register changes
value. For example, to disable continuous monitoring of window wa:
lmcwin disable /top/u1/wa
lmcwin release
Some windows are actually nets, and the lmcwin write command behaves more like a
continuous force on the net. The lmcwin release command disables the effect of a previous
lmcwin write command on a window net.
Memory arrays
A memory model usually makes the entire register array available as a window. In this case,
the window commands operate only on a single element at a time. The element is selected
as an array reference in the window instance specification. For example, to read element 5
from the window memory mem:
lmcwin read /top/u2/mem(5)
Logic Modeling hardware models can be used with ModelSim VHDL and Verilog. A
hardware model allows simulation of a device using the actual silicon installed as a
hardware model in one of Logic Modeling's hardware modeling systems. The hardware
modeling system is a network resource with a procedural interface that is accessed by the
simulator. This appendix describes how to use Logic Modeling hardware models with
ModelSim.
Note: Please refer to Logic Modeling documentation from Synopsys for details on using
the hardware modeler. This appendix only describes the specifics of using hardware
models with ModelSim SE.
The libhm entry points to the ModelSim dynamic link library that interfaces the foreign
architecture to the hardware modeler software. The libsfi entry points to the Logic
Modeling dynamic link library software that accesses the hardware modeler. The simulator
automatically loads both the libhm and libsfi libraries when it elaborates a hardware model
foreign architecture.
By default, the libhm entry points to the libhm.sl supplied in the ModelSim installation
directory indicated by the MODEL_TECH environment variable. ModelSim automatically
sets the MODEL_TECH environment variable to the appropriate directory containing the
executables and binaries for the current operating system. If you are running the Windows
operating system, then you must comment out the default libhm entry (precede the line
with the ";" character) and uncomment the libhm entry for the Windows operating system.
Uncomment the appropriate libsfi entry for your operating system, and replace <sfi_dir>
with the path to the hardware modeler software installation directory. In addition, you must
set the LM_LIB and LM_DIR environment variables as described in Logic Modeling
documentation from Synopsys.
Syntax
hm_entity
[-xe] [-xa] [-c] [-93] <shell software filename>
Arguments
-xe
Do not generate entity declarations.
-xa
Do not generate architecture bodies.
-c
Generate component declarations.
-93
Use extended identifiers where needed.
<shell software filename>
Hardware model shell software filename (see Logic Modeling documentation from
Synopsys for details on shell software files)
By default, the hm_entity tool writes an entity and foreign architecture to stdout for the
hardware model. Optionally, you can include the component declaration (-c), exclude the
entity (-xe), and exclude the architecture (-xa).
Once you have created the entity and foreign architecture, you must compile it into a
library. For example, the following commands compile the entity and foreign architecture
for a hardware model named LMTEST:
% hm_entity LMTEST.MDL > lmtest.vhd
% vlib lmc
% vcom -work lmc lmtest.vhd
To instantiate the hardware model in your VHDL design, you will also need to generate a
component declaration. If you have multiple hardware models, you may want to add all of
their component declarations to a package so that you can easily reference them in your
design. The following command writes the component declaration to stdout for the
LMTEST hardware model.
% hm_entity -c -xe -xa LMTEST.MDL
Paste the resulting component declaration into the appropriate place in your design or into
a package.
The following is an example of the entity and foreign architecture created by hm_entity for
the CY7C285 hardware model:
library ieee;
use ieee.std_logic_1164.all;
entity cy7c285 is
generic ( DelayRange : STRING := "Max" );
port ( A0 : in std_logic;
A1 : in std_logic;
A2 : in std_logic;
A3 : in std_logic;
A4 : in std_logic;
A5 : in std_logic;
A6 : in std_logic;
A7 : in std_logic;
A8 : in std_logic;
A9 : in std_logic;
A10 : in std_logic;
A11 : in std_logic;
A12 : in std_logic;
A13 : in std_logic;
A14 : in std_logic;
A15 : in std_logic;
CS : in std_logic;
O0 : out std_logic;
O1 : out std_logic;
O2 : out std_logic;
O3 : out std_logic;
O4 : out std_logic;
O5 : out std_logic;
O6 : out std_logic;
O7 : out std_logic;
W : inout std_logic );
end;
Entity details
• The entity name is the hardware model name (you can manually change this name if you
like).
• The port names are the same as the hardware model port names (these names must not be
changed). If the hardware model port name is not a valid VHDL identifier, then
hm_entity issues an error message. If hm_entity is invoked with the -93 option, then the
identifier is converted to an extended identifier, and the resulting entity must also be
compiled with the -93 option. Another option is to create a pin-name mapping file.
Consult the Logic Modeling documentation from Synopsys for details.
• The port types are std_logic. This data type supports the full range of hardware model
logic states.
• The DelayRange generic selects minimum, typical, or maximum delay values. Valid
values are "min", "typ", or "max" (the strings are not case-sensitive). The default is
"max".
Architecture details
• The first part of the foreign attribute string (hm_init) is the same for all hardware models.
• The second part ($MODEL_TECH/libhm.sl) is taken from the libhm entry in the
initialization file, modelsim.ini.
• The third part (CY7C285.MDL) is the shell software filename. This name correlates the
architecture with the hardware model at elaboration.
Vector ports
The entities generated by hm_entity only contain single-bit ports, never vectored ports.
However, for ease of use in component instantiations, you may want to create a custom
component declaration and component specification that groups ports into vectors. You can
also rename and reorder the ports in the component declaration. You can also reorder the
ports in the entity declaration, but you can't rename them!
The following is an example component declaration and specification that groups the
address and data ports of the CY7C285 hardware model:
component cy7c285
generic ( DelayRange : STRING := "Max");
port ( A : in std_logic_vector (15 downto 0);
CS : in std_logic;
O : out std_logic_vector (7 downto 0);
WAIT_PORT : inout std_logic );
end component;
1. GRANT OF LICENSE. The software programs you are installing, downloading, or have
acquired with this Agreement, including any updates, modifications, revisions, copies,
documentation and design data (“Software”) are copyrighted, trade secret and confidential
information of Mentor Graphics or its licensors who maintain exclusive title to all
Software and retain all rights not expressly granted by this Agreement. Mentor Graphics
grants to you, subject to payment of appropriate license fees, a nontransferable,
nonexclusive license to use Software solely: (a) in machine-readable, object-code form;
(b) for your internal business purposes; and (c) on the computer hardware or at the site for
which an applicable license fee is paid, or as authorized by Mentor Graphics. A site is
restricted to a one-half mile (800 meter) radius. Mentor Graphics’ standard policies and
programs, which vary depending on Software, license fees paid or service plan purchased,
apply to the following and are subject to change: (a) relocation of Software; (b) use of
Software, which may be limited, for example, to execution of a single session by a single
user on the authorized hardware or for a restricted period of time (such limitations may be
communicated and technically implemented through the use of authorization codes or
similar devices); (c) support services provided, including eligibility to receive telephone
support, updates, modifications, and revisions. Current standard policies and programs are
available upon request.
3. BETA CODE. Portions or all of certain Software may contain code for experimental
testing and evaluation (“Beta Code”), which may not be used without Mentor Graphics’
explicit authorization. Upon Mentor Graphics’ authorization, Mentor Graphics grants to
you a temporary, nontransferable, nonexclusive license for experimental use to test and
evaluate the Beta Code without charge for a limited period of time specified by Mentor
Graphics. This grant and your use of the Beta Code shall not be construed as marketing or
offering to sell a license to the Beta Code, which Mentor Graphics may choose not to
release commercially in any form. If Mentor Graphics authorizes you to use the Beta
Code, you agree to evaluate and test the Beta Code under normal conditions as directed by
Mentor Graphics. You will contact Mentor Graphics periodically during your use of the
Beta Code to discuss any malfunctions or suggested improvements. Upon completion of
your evaluation and testing, you will send to Mentor Graphics a written evaluation of the
Beta Code, including its strengths, weaknesses and recommended improvements. You
agree that any written evaluations and all inventions, product improvements,
modifications or developments that Mentor Graphics conceived or made during or
subsequent to this Agreement, including those based partly or wholly on your feedback,
will be the exclusive property of Mentor Graphics. Mentor Graphics will have exclusive
rights, title and interest in all such property. The provisions of this subsection shall survive
termination or expiration of this Agreement.
The terms of this Agreement, including without limitation, the licensing and assignment
provisions shall be binding upon your heirs, successors in interest and assigns. The
provisions of this section 4 shall survive the termination or expiration of this Agreement.
5. LIMITED WARRANTY.
5.1. Mentor Graphics warrants that during the warranty period Software, when properly
installed, will substantially conform to the functional specifications set forth in the
applicable user manual. Mentor Graphics does not warrant that Software will meet
your requirements or that operation of Software will be uninterrupted or error free.
The warranty period is 90 days starting on the 15th day after delivery or upon
installation, whichever first occurs. You must notify Mentor Graphics in writing of
any nonconformity within the warranty period. This warranty shall not be valid if
Software has been subject to misuse, unauthorized modification or installation.
MENTOR GRAPHICS' ENTIRE LIABILITY AND YOUR EXCLUSIVE REMEDY
SHALL BE, AT MENTOR GRAPHICS' OPTION, EITHER (A) REFUND OF THE
PRICE PAID UPON RETURN OF SOFTWARE TO MENTOR GRAPHICS OR (B)
MODIFICATION OR REPLACEMENT OF SOFTWARE THAT DOES NOT
MEET THIS LIMITED WARRANTY, PROVIDED YOU HAVE OTHERWISE
9. INFRINGEMENT.
9.1. Mentor Graphics will defend or settle, at its option and expense, any action brought
against you alleging that Software infringes a patent or copyright or misappropriates a
trade secret in the United States, Canada, Japan, or member state of the European
Patent Office. Mentor Graphics will pay any costs and damages finally awarded
against you that are attributable to the infringement action. You understand and agree
that as conditions to Mentor Graphics' obligations under this section you must:
(a) notify Mentor Graphics promptly in writing of the action; (b) provide Mentor
Graphics all reasonable information and assistance to defend or settle the action; and
(c) grant Mentor Graphics sole authority and control of the defense or settlement of
the action.
9.2. If an infringement claim is made, Mentor Graphics may, at its option and expense:
(a) replace or modify Software so that it becomes noninfringing; (b) procure for you
the right to continue using Software; or (c) require the return of Software and refund
to you any license fee paid, less a reasonable allowance for use.
9.3. Mentor Graphics has no liability to you if infringement is based upon: (a) the
combination of Software with any product not furnished by Mentor Graphics; (b) the
modification of Software other than by Mentor Graphics; (c) the use of other than a
current unaltered release of Software; (d) the use of Software as part of an infringing
process; (e) a product that you make, use or sell; (f) any Beta Code contained in
Software; (g) any Software provided by Mentor Graphics’ licensors who do not
provide such indemnification to Mentor Graphics’ customers; or (h) infringement by
you that is deemed willful. In the case of (h) you shall reimburse Mentor Graphics for
its attorney fees and other costs related to the action upon a final judgment.
10. TERM. This Agreement remains effective until expiration or termination. This
Agreement will immediately terminate upon notice if you exceed the scope of license
granted or otherwise fail to comply with the provisions of Sections 1, 2, or 4. For any
other material breach under this Agreement, Mentor Graphics may terminate this
Agreement upon 30 days written notice if you are in material breach and fail to cure such
breach within the 30-day notice period. If Software was provided for limited term use,
this Agreement will automatically expire at the end of the authorized term. Upon any
termination or expiration, you agree to cease all use of Software and return it to Mentor
Graphics or certify deletion and destruction of Software, including all copies, to Mentor
Graphics’ reasonable satisfaction.
11. EXPORT. Software is subject to regulation by local laws and United States government
agencies, which prohibit export or diversion of certain products, information about the
products, and direct products of the products to certain countries and certain persons. You
agree that you will not export any Software or direct product of Software in any manner
without first obtaining all necessary approval from appropriate local and United States
government agencies.
12. RESTRICTED RIGHTS NOTICE. Software was developed entirely at private expense
and is 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 the restrictions set forth in the license agreement under which Software was
obtained pursuant to DFARS 227.7202-3(a) or as set forth in subparagraphs (c)(1) and (2)
of the Commercial Computer Software - Restricted Rights clause at FAR 52.227-19, as
applicable. Contractor/manufacturer is Mentor Graphics Corporation, 8005 SW
Boeckman Road, Wilsonville, Oregon 97070-7777 USA.
13. THIRD PARTY BENEFICIARY. For any Software under this Agreement licensed by
Mentor Graphics from Microsoft or other licensors, Microsoft or the applicable licensor is
a third party beneficiary of this Agreement with the right to enforce the obligations set
forth herein.
14. AUDIT RIGHTS. With reasonable prior notice, Mentor Graphics shall have the right to
audit during your normal business hours all records and accounts as may contain
information regarding your compliance with the terms of this Agreement. Mentor
Graphics shall keep in confidence all information gained as a result of any audit. Mentor
Graphics shall only use or disclose such information as necessary to enforce its rights
under this Agreement.
17. PAYMENT TERMS AND MISCELLANEOUS. You will pay amounts invoiced, in
the currency specified on the applicable invoice, within 30 days from the date of such
invoice. This Agreement contains the parties' entire understanding relating to its subject
matter and supersedes all prior or contemporaneous agreements, including but not limited
to any purchase order terms and conditions, except valid license agreements related to the
subject matter of this Agreement (which are physically signed by you and an authorized
agent of Mentor Graphics) either referenced in the purchase order or otherwise governing
this subject matter. This Agreement may only be modified in writing by authorized
representatives of the parties. Waiver of terms or excuse of breach must be in writing and
shall not constitute subsequent consent, waiver or excuse. The prevailing party in any
legal action regarding the subject matter of this Agreement shall be entitled to recover, in
addition to other relief, reasonable attorneys' fees and expenses.
D defaults
restoring UM-520
deltas +define+ CR-359
explained UM-80 Define Clock dialog GR-188
data types definition (ID) of memory GR-170
Code Coverage UM-335 delay
database, functional coverage, saving UM-395 delta delays UM-80
Dataflow Options dialog GR-140 interconnect CR-378
Dataflow Page Setup dialog GR-138 modes for Verilog models UM-144
Dataflow window UM-300, GR-128 SDF files UM-439
automatic cell hiding GR-140, GR-141 stimulus delay, specifying GR-187
menu bar GR-129 +delay_mode_distributed CR-359
options GR-140, GR-141 +delay_mode_path CR-359
pan UM-305 +delay_mode_unit CR-359
zoom UM-305 +delay_mode_zero CR-360
see also windows, Dataflow window ’delayed CR-24
dataflow.bsm file UM-313 DelayFileOpen .ini file variable UM-532
dataset alias command CR-136 delaying test signal, Waveform Comparison GR-244
Dataset Browser UM-229, GR-49 delete command CR-146
dialog GR-49 deleting library contents UM-61
dataset clear command CR-137 delta collapsing UM-232
dataset close command CR-138 delta simulator state variable UM-542
dataset info command CR-139 deltas
dataset list command CR-140 collapsing in the List window GR-163
dataset open command CR-141 collapsing in WLF files CR-382
dataset rename command CR-142, CR-143 hiding in the List window CR-124, GR-163
Dataset Snapshot UM-231 in List window UM-265
dataset snapshot command CR-144 referencing simulator iteration
datasets UM-225 as a simulator state variable UM-542
environment command, specifying with CR-161 dependencies, checking CR-328
managing UM-229 dependent design units UM-73
openingdialogs describe command CR-147
Open File GR-39 descriptions of HDL items GR-203
reference UM-272 design library
restrict dataset prefix display UM-230 creating UM-60
test UM-273 logical name, assigning UM-62
DatasetSeparator .ini file variable UM-531 mapping search rules UM-63
debuggable SystemC objects UM-176 resource type UM-58
debugging VHDL design units UM-73
C code UM-399 working type UM-58
debugging the design, overview UM-26 design object icons, described GR-12
declarations, hiding implicit with explicit CR-318 Design Optimization dialog GR-70
default binding design portability and SystemC UM-168
BindAtCompile .ini file variable UM-527 design units UM-58
disabling UM-79 report of units simulated CR-426
default binding rules UM-79 Verilog
default clock UM-368 adding to a library CR-358
Default editor, changing UM-521 details
DefaultForceKind .ini file variable UM-531 code coverage GR-123
DefaultRadix .ini file variable UM-531 dialogs GR-49
DefaultRestartOptions variable UM-531, UM-539 Add file to Project GR-44
Index
profile interval command CR-226 override mapping for work directory with vcom CR-
profile off command CR-227 256, CR-317
profile on command CR-228 override mapping for work directory with vlog CR-
profile option command CR-229 366
profile reload command CR-230 overview UM-38
profile report command CR-231, UM-331 propagation, preventing X propagation CR-378
Profile Report dialog GR-93, GR-197 Properties (memory) dialog GR-183
Profiler UM-317 property list command CR-234
%parent fields UM-325 property wave command CR-235
clear profile data UM-321 Protect .ini file variable (VLOG) UM-526
enabling memory profiling UM-319 ‘protect compiler directive UM-155
enabling statistical sampling UM-321 protected types UM-101
getting started UM-319 PSL
handling large files UM-320 assume directives UM-363
Hierarchical View UM-325 endpoint directives UM-398
interpreting data UM-323 standard supported UM-30
memory allocation UM-318 PSL assertions UM-359
memory allocation profiling UM-321 see also assertions
profile report command UM-331 pulse error state CR-388
Profile Report dialog UM-332, GR-93 push command CR-237
Ranked View UM-324 pwd command CR-238
report option UM-331
reporting GR-93
results, viewing UM-324 Q
statistical sampling UM-318
quick reference
Structural View UM-326
table of ModelSim tasks UM-23
unsupported on Opteron UM-317
QuickSim II logfile format CR-413
view_profile command UM-324
Quiet .ini file variable
viewing profile details UM-327
VCOM UM-527
Programming Language Interface UM-158, UM-560
Quiet .ini file variable (VLOG) UM-526
Project Compiler Settings dialog GR-50
quietly command CR-239
Project Settings dialog GR-57
quit command CR-240
project tab
information in UM-45
sorting UM-45 R
Projects
MODELSIM environment variable UM-521 race condition, problems with event order UM-132
projects UM-37 radix
accessing from the command line UM-55 changing in Objects, Locals, Dataflow, List, and
adding files to UM-41 Wave windows CR-241
benefits UM-38 character strings, displaying CR-354
code coverage settings UM-338 default, DefaultRadix variable UM-531
compile order UM-46 List window UM-259
changing UM-46 of signals being examined CR-163
compiler properties in UM-52 of signals in Wave window CR-54
compiling files UM-43 specifying in Memory window GR-183
creating UM-40 Wave window UM-255
creating simulation configurations UM-48 radix command CR-241
folders in UM-50 range checking UM-74
grouping files in UM-47 disabling CR-315
loading a design UM-44 enabling CR-316
Index
Y
-y CR-366
Z
zero delay elements UM-80
zero delay mode UM-145
zero-delay loop, infinite UM-81
zero-delay oscillation UM-81
zero-delay race condition UM-132
zoom
Dataflow window UM-305
from Wave toolbar buttons UM-249
saving range with bookmarks UM-250
with the mouse UM-249
zooming window panes GR-260