aboutsummaryrefslogtreecommitdiffstats
path: root/manual/PRESENTATION_Prog.tex
blob: b0390cb99771aaa82fb1699d3e3f13255ff7a1a6 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
\section{Writing Yosys extensions in C++}

\begin{frame}
\sectionpage
\end{frame}

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

\subsection{Program Components and Data Formats}

\begin{frame}{\subsecname}
\begin{center}
\begin{tikzpicture}[scale=0.6, every node/.style={transform shape}]
	\tikzstyle{process} = [draw, fill=green!10, rectangle, minimum height=3em, minimum width=10em, node distance=15em]
	\tikzstyle{data} = [draw, fill=blue!10, ellipse, minimum height=3em, minimum width=7em, node distance=15em]
	\node[process] (vlog) {Verilog Frontend};
	\node[process, dashed, fill=green!5] (vhdl) [right of=vlog] {VHDL Frontend};
	\node[process] (ilang) [right of=vhdl] {Other Frontends};
	\node[data] (ast) [below of=vlog, node distance=5em, xshift=7.5em] {AST};
	\node[process] (astfe) [below of=ast, node distance=5em] {AST Frontend};
	\node[data] (rtlil) [below of=astfe, node distance=5em, xshift=7.5em] {RTLIL};
	\node[process] (pass) [right of=rtlil, node distance=5em, xshift=7.5em] {Passes};
	\node[process] (vlbe) [below of=rtlil, node distance=7em, xshift=-13em] {Verilog Backend};
	\node[process] (ilangbe) [below of=rtlil, node distance=7em, xshift=0em] {RTLIL Backend};
	\node[process, fill=green!5] (otherbe) [below of=rtlil, node distance=7em, xshift=+13em] {Other Backends};

	\draw[-latex] (vlog) -- (ast);
	\draw[-latex] (vhdl) -- (ast);
	\draw[-latex] (ast) -- (astfe);
	\draw[-latex] (astfe) -- (rtlil);
	\draw[-latex] (ilang) -- (rtlil);
	\draw[latex-latex] (rtlil) -- (pass);
	\draw[-latex] (rtlil) -- (vlbe);
	\draw[-latex] (rtlil) -- (ilangbe);
	\draw[-latex] (rtlil) -- (otherbe);
\end{tikzpicture}
\end{center}
\end{frame}

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

\subsection{Simplified RTLIL Entity-Relationship Diagram}

\begin{frame}{\subsecname}
Between passses and frontends/backends the design is stored in Yosys' internal
RTLIL (RTL Intermediate Language) format. For writing Yosys extensions it is
key to understand this format.

\bigskip
\begin{center}
\begin{tikzpicture}[scale=0.6, every node/.style={transform shape}]
	\tikzstyle{entity} = [draw, fill=gray!10, rectangle, minimum height=3em, minimum width=7em, node distance=5em, font={\ttfamily}]
	\node[entity] (design) {RTLIL::Design};
	\node[entity] (module) [right of=design, node distance=11em] {RTLIL::Module} edge [-latex] node[above] {\tiny 1 \hskip3em N} (design);

	\node[entity] (process) [fill=green!10, right of=module, node distance=10em] {RTLIL::Process} (process.west) edge [-latex] (module);
	\node[entity] (memory) [fill=red!10, below of=process] {RTLIL::Memory} edge [-latex] (module);
	\node[entity] (wire) [fill=blue!10, above of=process] {RTLIL::Wire} (wire.west) edge [-latex] (module);
	\node[entity] (cell) [fill=blue!10, above of=wire] {RTLIL::Cell} (cell.west) edge [-latex] (module);

	\node[entity] (case) [fill=green!10, right of=process, node distance=10em] {RTLIL::CaseRule} edge [latex-latex] (process);
	\node[entity] (sync) [fill=green!10, above of=case] {RTLIL::SyncRule} edge [-latex] (process);
	\node[entity] (switch) [fill=green!10, below of=case] {RTLIL::SwitchRule} edge [-latex] (case);
	\draw[latex-] (switch.east) -- ++(1em,0) |- (case.east);
\end{tikzpicture}
\end{center}
\end{frame}

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

\subsection{RTLIL without memories and processes}

\begin{frame}[fragile]{\subsecname}
After the commands {\tt proc} and {\tt memory} (or {\tt memory -nomap}), we are
left with a much simpler version of RTLIL:

\begin{center}
\begin{tikzpicture}[scale=0.6, every node/.style={transform shape}]
	\tikzstyle{entity} = [draw, fill=gray!10, rectangle, minimum height=3em, minimum width=7em, node distance=5em, font={\ttfamily}]
	\node[entity] (design) {RTLIL::Design};
	\node[entity] (module) [right of=design, node distance=11em] {RTLIL::Module} edge [-latex] node[above] {\tiny 1 \hskip3em N} (design);

	\node[entity] (wire) [fill=blue!10, right of=module, node distance=10em] {RTLIL::Wire} (wire.west) edge [-latex] (module);
	\node[entity] (cell) [fill=blue!10, above of=wire] {RTLIL::Cell} (cell.west) edge [-latex] (module);
\end{tikzpicture}
\end{center}

\bigskip
Many commands simply choose to only work on this simpler version:
\begin{lstlisting}[xleftmargin=0.5cm, basicstyle=\ttfamily\fontsize{8pt}{10pt}\selectfont]
for (RTLIL::Module *module : design->selected_modules() {
    if (module->has_memories_warn() || module->has_processes_warn())
        continue;
    ....
}
\end{lstlisting}

For simplicity we only discuss this version of RTLIL in this presentation.
\end{frame}

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

\subsection{Using dump and show commands}

\begin{frame}{\subsecname}
\begin{itemize}
\item The {\tt dump} command prints the design (or parts of it) in the text representation of RTLIL.

\bigskip
\item The {\tt show} command visualizes how the components in the design are connected.
\end{itemize}

\bigskip
When trying to understand what a command does, create a small test case and
look at the output of {\tt dump} and {\tt show} before and after the command
has been executed.
\end{frame}

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

\subsection{The RTLIL Data Structures}

\begin{frame}{\subsecname}
The RTLIL data structures are simple structs utilizing {\tt pool<>} and
{\tt dict<>} containers (drop-in replacements for {\tt
std::unordered\_set<>} and {\tt std::unordered\_map<>}).

\bigskip
\begin{itemize}
\item Most operations are performed directly on the RTLIL structs without
setter or getter functions.

\bigskip
\item In debug builds a consistency checker is run over the in-memory design
between commands to make sure that the RTLIL representation is intact.

\bigskip
\item Most RTLIL structs have helper methods that perform the most common operations.
\end{itemize}

\bigskip
See {\tt yosys/kernel/rtlil.h} for details.
\end{frame}

\subsubsection{RTLIL::IdString}

\begin{frame}{\subsubsecname}{}
{\tt RTLIL::IdString} in many ways behave like a {\tt std::string}. It is used
for names of RTLIL objects. Internally a RTLIL::IdString object is only a
single integer.

\medskip
The first character of a {\tt RTLIL::IdString} specifies if the name is {\it public\/} or {\it private\/}:

\medskip
\begin{itemize}
\item {\tt RTLIL::IdString[0] == '\textbackslash\textbackslash'}: \\
This is a public name. Usually this means it is a name that was declared in a Verilog file.

\bigskip
\item {\tt RTLIL::IdString[0] == '\$'}: \\
This is a private name. It was assigned by Yosys.
\end{itemize}

\bigskip
Use the {\tt NEW\_ID} macro to create a new unique private name.
\end{frame}

\subsubsection{RTLIL::Design and RTLIL::Module}

\begin{frame}[t, fragile]{\subsubsecname}
The {\tt RTLIL::Design} and {\tt RTLIL::Module} structs are the top-level RTLIL
data structures. Yosys always operates on one active design, but can hold many designs in memory.

\bigskip
\begin{lstlisting}[xleftmargin=1cm, basicstyle=\ttfamily\fontsize{8pt}{10pt}\selectfont, language=C++]
struct RTLIL::Design {
    dict<RTLIL::IdString, RTLIL::Module*> modules_;
    ...
};

struct RTLIL::Module {
    RTLIL::IdString name;
    dict<RTLIL::IdString, RTLIL::Wire*> wires_;
    dict<RTLIL::IdString, RTLIL::Cell*> cells_;
    std::vector<RTLIL::SigSig> connections_;
    ...
};
\end{lstlisting}

(Use the various accessor functions instead of directly working with the {\tt *\_} members.)
\end{frame}

\subsubsection{The RTLIL::Wire Structure}

\begin{frame}[t, fragile]{\subsubsecname}
Each wire in the design is represented by a {\tt RTLIL::Wire} struct:

\medskip
\begin{lstlisting}[xleftmargin=1cm, basicstyle=\ttfamily\fontsize{8pt}{10pt}\selectfont, language=C++]
struct RTLIL::Wire {
    RTLIL::IdString name;
    int width, start_offset, port_id;
    bool port_input, port_output;
    ...
};
\end{lstlisting}

\medskip
\hfil\begin{tabular}{p{3cm}l}
{\tt width} \dotfill & The total number of bits. E.g. 10 for {\tt [9:0]}. \\
{\tt start\_offset} \dotfill & The lowest bit index. E.g. 3 for {\tt [5:3]}. \\
{\tt port\_id} \dotfill & Zero for non-ports. Positive index for ports. \\
{\tt port\_input} \dotfill & True for {\tt input} and {\tt inout} ports. \\
{\tt port\_output} \dotfill & True for {\tt output} and {\tt inout} ports. \\
\end{tabular}
\end{frame}

\subsubsection{RTLIL::State and RTLIL::Const}

\begin{frame}[t, fragile]{\subsubsecname}
The {\tt RTLIL::State} enum represents a simple 1-bit logic level:

\smallskip
\begin{lstlisting}[xleftmargin=1cm, basicstyle=\ttfamily\fontsize{8pt}{10pt}\selectfont, language=C++]
enum RTLIL::State {
    S0 = 0,
    S1 = 1,
    Sx = 2, // undefined value or conflict
    Sz = 3, // high-impedance / not-connected
    Sa = 4, // don't care (used only in cases)
    Sm = 5  // marker (used internally by some passes)
};
\end{lstlisting}

\bigskip
The {\tt RTLIL::Const} struct represents a constant multi-bit value:

\smallskip
\begin{lstlisting}[xleftmargin=1cm, basicstyle=\ttfamily\fontsize{8pt}{10pt}\selectfont, language=C++]
struct RTLIL::Const {
    std::vector<RTLIL::State> bits;
    ...
};
\end{lstlisting}

\bigskip
Notice that Yosys is not using special {\tt VCC} or {\tt GND} driver cells to represent constants. Instead
constants are part of the RTLIL representation itself.
\end{frame}

\subsubsection{The RTLIL::SigSpec Structure}

\begin{frame}[t, fragile]{\subsubsecname}
The {\tt RTLIL::SigSpec} struct represents a signal vector. Each bit can either be a bit from a wire
or a constant value.

\bigskip
\begin{lstlisting}[xleftmargin=1cm, basicstyle=\ttfamily\fontsize{8pt}{10pt}\selectfont, language=C++]
struct RTLIL::SigBit
{
    RTLIL::Wire *wire;
    union {
        RTLIL::State data; // used if wire == NULL
        int offset;        // used if wire != NULL
    };
    ...
};

struct RTLIL::SigSpec {
    std::vector<RTLIL::SigBit> bits_; // LSB at index 0
    ...
};
\end{lstlisting}

\bigskip
The {\tt RTLIL::SigSpec} struct has a ton of additional helper methods to compare, analyze, and
manipulate instances of {\tt RTLIL::SigSpec}.
\end{frame}

\subsubsection{The RTLIL::Cell Structure}

\begin{frame}[t, fragile]{\subsubsecname (1/2)}
The {\tt RTLIL::Cell} struct represents an instance of a module or library cell.

\smallskip
The ports of the cell
are associated with {\tt RTLIL::SigSpec} instances and the parameters are associated with {\tt RTLIL::Const}
instances:

\bigskip
\begin{lstlisting}[xleftmargin=1cm, basicstyle=\ttfamily\fontsize{8pt}{10pt}\selectfont, language=C++]
struct RTLIL::Cell {
    RTLIL::IdString name, type;
    dict<RTLIL::IdString, RTLIL::SigSpec> connections_;
    dict<RTLIL::IdString, RTLIL::Const> parameters;
    ...
};
\end{lstlisting}

\bigskip
The {\tt type} may refer to another module in the same design, a cell name from a cell library, or a
cell name from the internal cell library:

\begin{lstlisting}[xleftmargin=1cm, basicstyle=\ttfamily\fontsize{6pt}{7pt}\selectfont]
$not $pos $neg $and $or $xor $xnor $reduce_and $reduce_or $reduce_xor $reduce_xnor
$reduce_bool $shl $shr $sshl $sshr $lt $le $eq $ne $eqx $nex $ge $gt $add $sub $mul $div $mod
$divfloor $modfloor $pow $logic_not $logic_and $logic_or $mux $pmux $slice $concat $lut $assert $sr $dff
$dffsr $adff $dlatch $dlatchsr $memrd $memwr $mem $fsm $_NOT_ $_AND_ $_OR_ $_XOR_ $_MUX_ $_SR_NN_
$_SR_NP_ $_SR_PN_ $_SR_PP_ $_DFF_N_ $_DFF_P_ $_DFF_NN0_ $_DFF_NN1_ $_DFF_NP0_ $_DFF_NP1_ $_DFF_PN0_
$_DFF_PN1_ $_DFF_PP0_ $_DFF_PP1_ $_DFFSR_NNN_ $_DFFSR_NNP_ $_DFFSR_NPN_ $_DFFSR_NPP_ $_DFFSR_PNN_
$_DFFSR_PNP_ $_DFFSR_PPN_ $_DFFSR_PPP_ $_DLATCH_N_ $_DLATCH_P_ $_DLATCHSR_NNN_ $_DLATCHSR_NNP_
$_DLATCHSR_NPN_ $_DLATCHSR_NPP_ $_DLATCHSR_PNN_ $_DLATCHSR_PNP_ $_DLATCHSR_PPN_ $_DLATCHSR_PPP_
\end{lstlisting}
\end{frame}

\begin{frame}[t, fragile]{\subsubsecname (2/2)}
Simulation models (i.e. {\it documentation\/} :-) for the internal cell library:

\smallskip
\hskip2em {\tt yosys/techlibs/common/simlib.v} and \\
\hskip2em {\tt yosys/techlibs/common/simcells.v}

\bigskip
The lower-case cell types (such as {\tt \$and}) are parameterized cells of variable
width. This so-called {\it RTL Cells\/} are the cells described in {\tt simlib.v}.

\bigskip
The upper-case cell types (such as {\tt \$\_AND\_}) are single-bit cells that are not
parameterized. This so-called {\it Internal Logic Gates} are the cells described
in {\tt simcells.v}.

\bigskip
The consistency checker also checks the interfaces to the internal cell library.
If you want to use private cell types for your own purposes, use the {\tt \$\_\_}-prefix
to avoid name collisions.
\end{frame}

\subsubsection{Connecting wires or constant drivers}

\begin{frame}[t, fragile]{\subsubsecname}
Additional connections between wires or between wires and constants are modelled using
{\tt RTLIL::Module::connections}:

\bigskip
\begin{lstlisting}[xleftmargin=1cm, basicstyle=\ttfamily\fontsize{8pt}{10pt}\selectfont, language=C++]
typedef std::pair<RTLIL::SigSpec, RTLIL::SigSpec> RTLIL::SigSig;

struct RTLIL::Module {
    ...
    std::vector<RTLIL::SigSig> connections_;
    ...
};
\end{lstlisting}

\bigskip
{\tt RTLIL::SigSig::first} is the driven signal and {\tt RTLIL::SigSig::second} is the driving signal.
Example usage (setting wire {\tt foo} to value {\tt 42}):
\begin{lstlisting}[xleftmargin=1cm, basicstyle=\ttfamily\fontsize{8pt}{10pt}\selectfont, language=C++]
module->connect(module->wire("\\foo"),
                RTLIL::SigSpec(42, module->wire("\\foo")->width));
\end{lstlisting}
\end{frame}

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

\subsection{Creating modules from scratch}

\begin{frame}[t, fragile]{\subsecname}
Let's create the following module using the RTLIL API:

\smallskip
\begin{lstlisting}[xleftmargin=1cm, basicstyle=\ttfamily\fontsize{8pt}{10pt}\selectfont, language=Verilog]
module absval(input signed [3:0] a, output [3:0] y);
    assign y = a[3] ? -a : a;
endmodule
\end{lstlisting}

\smallskip
\begin{lstlisting}[xleftmargin=1cm, basicstyle=\ttfamily\fontsize{8pt}{10pt}\selectfont, language=C++]
RTLIL::Module *module = new RTLIL::Module;
module->name = "\\absval";

RTLIL::Wire *a = module->addWire("\\a", 4);
a->port_input = true;
a->port_id = 1;

RTLIL::Wire *y = module->addWire("\\y", 4);
y->port_output = true;
y->port_id = 2;

RTLIL::Wire *a_inv = module->addWire(NEW_ID, 4);
module->addNeg(NEW_ID, a, a_inv, true);
module->addMux(NEW_ID, a, a_inv, RTLIL::SigSpec(a, 1, 3), y);

module->fixup_ports();
\end{lstlisting}
\end{frame}

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

\subsection{Modifying modules}

\begin{frame}{\subsecname}
Most commands modify existing modules, not create new ones.

When modifying existing modules, stick to the following DOs and DON'Ts:

\begin{itemize}
\item Do not remove wires. Simply disconnect them and let a successive {\tt clean} command worry about removing it.

\item Use {\tt module->fixup\_ports()} after changing the {\tt port\_*} properties of wires.

\item You can safely remove cells or change the {\tt connections} property of a cell, but be careful when
changing the size of the {\tt SigSpec} connected to a cell port.

\item Use the {\tt SigMap} helper class (see next slide) when you need a unique handle for each signal bit.
\end{itemize}
\end{frame}

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

\subsection{Using the SigMap helper class}

\begin{frame}[t, fragile]{\subsecname}
Consider the following module:

\smallskip
\begin{lstlisting}[xleftmargin=1cm, basicstyle=\ttfamily\fontsize{8pt}{10pt}\selectfont, language=Verilog]
module test(input a, output x, y);
    assign x = a, y = a;
endmodule
\end{lstlisting}

In this case {\tt a}, {\tt x}, and {\tt y} are all different names for the same signal. However:

\smallskip
\begin{lstlisting}[xleftmargin=1cm, basicstyle=\ttfamily\fontsize{8pt}{10pt}\selectfont, language=C++]
RTLIL::SigSpec a(module->wire("\\a")), x(module->wire("\\x")),
                                       y(module->wire("\\y"));
log("%d %d %d\n", a == x, x == y, y == a); // will print "0 0 0"
\end{lstlisting}

The {\tt SigMap} helper class can be used to map all such aliasing signals to a
unique signal from the group (usually the wire that is directly driven by a cell or port).

\smallskip
\begin{lstlisting}[xleftmargin=1cm, basicstyle=\ttfamily\fontsize{8pt}{10pt}\selectfont, language=C++]
SigMap sigmap(module);
log("%d %d %d\n", sigmap(a) == sigmap(x), sigmap(x) == sigmap(y),
                  sigmap(y) == sigmap(a)); // will print "1 1 1"
\end{lstlisting}
\end{frame}

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

\subsection{Printing log messages}

\begin{frame}[t, fragile]{\subsecname}
The {\tt log()} function is a {\tt printf()}-like function that can be used to create log messages.

\medskip
Use {\tt log\_signal()} to create a C-string for a SigSpec object\footnote[frame]{The pointer returned
by {\tt log\_signal()} is automatically freed by the log framework at a later time.}:
\begin{lstlisting}[xleftmargin=1cm, basicstyle=\ttfamily\fontsize{8pt}{10pt}\selectfont, language=C++]
log("Mapped signal x: %s\n", log_signal(sigmap(x)));
\end{lstlisting}

\medskip
Use {\tt log\_id()} to create a C-string for an {\tt RTLIL::IdString}:
\begin{lstlisting}[xleftmargin=1cm, basicstyle=\ttfamily\fontsize{8pt}{10pt}\selectfont, language=C++]
log("Name of this module: %s\n", log_id(module->name));
\end{lstlisting}

\medskip
Use {\tt log\_header()} and {\tt log\_push()}/{\tt log\_pop()} to structure log messages:
\begin{lstlisting}[xleftmargin=1cm, basicstyle=\ttfamily\fontsize{8pt}{10pt}\selectfont, language=C++]
log_header(design, "Doing important stuff!\n");
log_push();
for (int i = 0; i < 10; i++)
    log("Log message #%d.\n", i);
log_pop();
\end{lstlisting}
\end{frame}

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

\subsection{Error handling}

\begin{frame}[t, fragile]{\subsecname}
Use {\tt log\_error()} to report a non-recoverable error:

\medskip
\begin{lstlisting}[xleftmargin=1cm, basicstyle=\ttfamily\fontsize{8pt}{10pt}\selectfont, language=C++]
if (design->modules.count(module->name) != 0)
    log_error("A module with the name %s already exists!\n",
            RTLIL::id2cstr(module->name));
\end{lstlisting}

\bigskip
Use {\tt log\_cmd\_error()} to report a recoverable error:
\begin{lstlisting}[xleftmargin=1cm, basicstyle=\ttfamily\fontsize{8pt}{10pt}\selectfont, language=C++]
if (design->selection_stack.back().empty())
    log_cmd_error("This command can't operator on an empty selection!\n");
\end{lstlisting}

\bigskip
Use {\tt log\_assert()} and {\tt log\_abort()} instead of {\tt assert()} and {\tt abort()}.
\end{frame}

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

\subsection{Creating a command}

\begin{frame}[t, fragile]{\subsecname}
Simply create a global instance of a class derived from {\tt Pass} to create
a new yosys command:

\bigskip
\begin{lstlisting}[xleftmargin=1cm, basicstyle=\ttfamily\fontsize{8pt}{10pt}\selectfont, language=C++]
#include "kernel/yosys.h"
USING_YOSYS_NAMESPACE

struct MyPass : public Pass {
    MyPass() : Pass("my_cmd", "just a simple test") { }
    virtual void execute(std::vector<std::string> args, RTLIL::Design *design)
    {
        log("Arguments to my_cmd:\n");
        for (auto &arg : args)
            log("  %s\n", arg.c_str());

        log("Modules in current design:\n");
        for (auto mod : design->modules())
            log("  %s (%d wires, %d cells)\n", log_id(mod),
                    GetSize(mod->wires()), GetSize(mod->cells()));
    }
} MyPass;
\end{lstlisting}
\end{frame}

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

\subsection{Creating a plugin}

\begin{frame}[fragile]{\subsecname}
Yosys can be extended by adding additional C++ code to the Yosys code base, or
by loading plugins into Yosys.

\bigskip
Use the following command to compile a Yosys plugin:
\begin{lstlisting}[xleftmargin=1cm, basicstyle=\ttfamily\fontsize{8pt}{10pt}\selectfont]
yosys-config --exec --cxx --cxxflags --ldflags \
             -o my_cmd.so -shared my_cmd.cc --ldlibs
\end{lstlisting}

\bigskip
Or shorter:
\begin{lstlisting}[xleftmargin=1cm, basicstyle=\ttfamily\fontsize{8pt}{10pt}\selectfont]
yosys-config --build my_cmd.so my_cmd.cc
\end{lstlisting}

\bigskip
Load the plugin using the yosys {\tt -m} option:
\begin{lstlisting}[xleftmargin=1cm, basicstyle=\ttfamily\fontsize{8pt}{10pt}\selectfont]
yosys -m ./my_cmd.so -p 'my_cmd foo bar'
\end{lstlisting}
\end{frame}

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

\subsection{Summary}

\begin{frame}{\subsecname}
\begin{itemize}
\item Writing Yosys extensions is very straight-forward.
\item \dots and even simpler if you don't need RTLIL::Memory or RTLIL::Process objects.

\bigskip
\item Writing synthesis software? Consider learning the Yosys API and make your work
part of the Yosys framework.
\end{itemize}

\bigskip
\bigskip
\begin{center}
Questions?
\end{center}

\bigskip
\bigskip
\begin{center}
\url{https://yosyshq.net/yosys/}
\end{center}
\end{frame}
a> 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 3394 3395 3396 3397 3398 3399 3400 3401 3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413 3414 3415 3416 3417 3418 3419 3420 3421 3422 3423 3424 3425 3426 3427 3428 3429 3430 3431 3432 3433 3434 3435 3436 3437 3438 3439 3440 3441 3442 3443 3444 3445 3446 3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464 3465 3466 3467 3468 3469 3470 3471 3472 3473 3474 3475 3476 3477 3478 3479 3480 3481 3482 3483 3484 3485 3486 3487 3488 3489 3490 3491 3492 3493 3494 3495 3496 3497 3498 3499 3500 3501 3502 3503 3504 3505 3506 3507 3508 3509 3510 3511 3512 3513 3514 3515 3516 3517 3518 3519 3520 3521 3522 3523 3524 3525 3526 3527 3528 3529 3530 3531 3532 3533 3534 3535 3536 3537 3538 3539 3540 3541 3542 3543 3544 3545 3546 3547 3548 3549 3550 3551 3552 3553 3554 3555 3556 3557 3558 3559 3560 3561 3562 3563 3564 3565 3566 3567 3568 3569 3570
--  Iir to ortho translator.
--  Copyright (C) 2002 - 2014 Tristan Gingold
--
--  This program is free software: you can redistribute it and/or modify
--  it under the terms of the GNU General Public License as published by
--  the Free Software Foundation, either version 2 of the License, or
--  (at your option) any later version.
--
--  This program is distributed in the hope that it will be useful,
--  but WITHOUT ANY WARRANTY; without even the implied warranty of
--  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
--  GNU General Public License for more details.
--
--  You should have received a copy of the GNU General Public License
--  along with this program.  If not, see <gnu.org/licenses>.

with Vhdl.Errors; use Vhdl.Errors;
with Files_Map;
with Vhdl.Utils; use Vhdl.Utils;
with Vhdl.Std_Package; use Vhdl.Std_Package;
with Vhdl.Canon;
with Translation; use Translation;
with Trans.Chap2;
with Trans.Chap3;
with Trans.Chap5;
with Trans.Chap6;
with Trans.Chap7;
with Trans.Chap8;
with Trans.Chap9;
with Trans.Chap14;
with Trans.Rtis;
with Trans.Helpers2; use Trans.Helpers2;
with Trans_Decls; use Trans_Decls;
with Trans.Foreach_Non_Composite;

package body Trans.Chap4 is
   use Trans.Helpers;

   --  Get the ortho type for an object of mode MODE.
   function Get_Object_Type (Tinfo : Type_Info_Acc; Kind : Object_Kind_Type)
                                return O_Tnode is
   begin
      case Tinfo.Type_Mode is
         when Type_Mode_Complex_Record
           | Type_Mode_Complex_Array
           | Type_Mode_Protected =>
            --  For a complex type, use a pointer.
            return Tinfo.Ortho_Ptr_Type (Kind);
         when others =>
            return Tinfo.Ortho_Type (Kind);
      end case;
   end Get_Object_Type;

   --  Return the pointer type for Tinfo.
   --  For a fat array, this is the fat pointer to slightly optimize accesses.
   function Get_Object_Ptr_Type
     (Tinfo : Type_Info_Acc; Kind : Object_Kind_Type) return O_Tnode is
   begin
      if Tinfo.Type_Mode in Type_Mode_Unbounded then
         --  Fat pointers are already pointers, no need to create an
         --  additional indirection.
         return Tinfo.Ortho_Type (Kind);
      else
         if Kind = Mode_Signal
           and then Tinfo.Type_Mode in Type_Mode_Scalar
         then
            --  A scalar signal is already a pointer.
            return Tinfo.Ortho_Type (Kind);
         else
            return Tinfo.Ortho_Ptr_Type (Kind);
         end if;
      end if;
   end Get_Object_Ptr_Type;

   function Lop2M
     (Obj_Ptr : O_Lnode; Tinfo : Type_Info_Acc; Mode : Object_Kind_Type)
     return Mnode is
   begin
      if (Mode = Mode_Signal
            and then Tinfo.Type_Mode in Type_Mode_Scalar)
        or else Tinfo.Type_Mode in Type_Mode_Unbounded
      then
         return Lv2M (Obj_Ptr, Tinfo, Mode);
      else
         return Lp2M (Obj_Ptr, Tinfo, Mode);
      end if;
   end Lop2M;

   procedure Assign_Obj_Ptr (Dest : Mnode; Src : Mnode)
   is
      Mode : constant Object_Kind_Type := Get_Object_Kind (Dest);
      Tinfo : constant Type_Info_Acc := Get_Type_Info (Dest);
   begin
      pragma Assert (Mode = Get_Object_Kind (Src));
      pragma Assert (Tinfo.Type_Mode = Get_Type_Info (Src).Type_Mode);
      if Tinfo.Type_Mode in Type_Mode_Unbounded then
         Copy_Fat_Pointer (Stabilize (Dest), Stabilize (Src));
      else
         if Mode = Mode_Signal
           and then Tinfo.Type_Mode in Type_Mode_Scalar
         then
            New_Assign_Stmt (M2Lv (Dest), M2E (Src));
         else
            New_Assign_Stmt (M2Lp (Dest), M2Addr (Src));
         end if;
      end if;
   end Assign_Obj_Ptr;

   procedure Create_Object (El : Iir)
   is
      Obj_Type : O_Tnode;
      Info     : Object_Info_Acc;
      Tinfo    : Type_Info_Acc;
      Def      : Iir;
      Val      : constant Iir := Get_Default_Value (El);
      Storage  : O_Storage;
      Deferred : Iir;
   begin
      --  Be sure the object type was translated.
      if Get_Kind (El) = Iir_Kind_Constant_Declaration
        and then Get_Deferred_Declaration_Flag (El) = False
        and then Get_Deferred_Declaration (El) /= Null_Iir
      then
         --  This is a full constant declaration which completes a previous
         --  incomplete constant declaration.
         --
         --  Do not create the subtype of this full constant declaration,
         --  since it was already created by the deferred declaration.
         --  Use the type of the deferred declaration.
         Deferred := Get_Deferred_Declaration (El);
         Def := Get_Type (Deferred);
         Info := Get_Info (Deferred);
         Set_Info (El, Info);
      else
         Chap3.Translate_Object_Subtype_Indication (El);
         Info := Add_Info (El, Kind_Object);
         Def := Get_Type (El);
      end if;

      Tinfo := Get_Info (Def);
      Obj_Type := Get_Object_Type (Tinfo, Mode_Value);

      case Get_Kind (El) is
         when Iir_Kind_Variable_Declaration
            | Iir_Kind_Interface_Constant_Declaration =>
            Info.Object_Var :=
              Create_Var (Create_Var_Identifier (El), Obj_Type);
         when Iir_Kind_Constant_Declaration =>
            if Get_Deferred_Declaration (El) /= Null_Iir then
               --  This is a full constant declaration (in a body) of a
               --  deferred constant declaration (in a package).
               Storage := O_Storage_Public;
            else
               Storage := Global_Storage;
            end if;
            if Info.Object_Var = Null_Var then
               --  Not a full constant declaration (ie a value for an
               --   already declared constant).
               --  Must create the declaration.
               if Chap7.Is_Static_Constant (El) then
                  Info.Object_Static := True;
                  Info.Object_Var := Create_Global_Const
                    (Create_Identifier (El), Obj_Type, Global_Storage,
                     O_Cnode_Null);
               else
                  Info.Object_Static := False;
                  Info.Object_Var := Create_Var
                    (Create_Var_Identifier (El), Obj_Type, Global_Storage);
               end if;
            end if;
            if Get_Deferred_Declaration (El) = Null_Iir
              and then Info.Object_Static
              and then Storage /= O_Storage_External
            then
               --  Deferred constant are never considered as locally static.
               --  FIXME: to be improved ?

               --  open_temp/close_temp only required for transient types.
               Open_Temp;
               Define_Global_Const
                 (Info.Object_Var,
                  Chap7.Translate_Static_Expression (Val, Def));
               Close_Temp;
            end if;
         when others =>
            Error_Kind ("create_objet", El);
      end case;
   end Create_Object;

   procedure Create_Signal (Decl : Iir)
   is
      Sig_Type_Def : constant Iir := Get_Type (Decl);
      Type_Info    : Type_Info_Acc;
      Info         : Signal_Info_Acc;
   begin
      if Get_Kind (Decl) /= Iir_Kind_Guard_Signal_Declaration then
         --  No subtype indication for guard signals (and its type is boolean).
         Chap3.Translate_Object_Subtype_Indication (Decl);
      end if;

      Type_Info := Get_Info (Sig_Type_Def);
      Info := Add_Info (Decl, Kind_Signal);

      Info.Signal_Sig := Create_Var
        (Create_Var_Identifier (Decl, "_SIG", 0),
         Get_Object_Type (Type_Info, Mode_Signal));

      if Get_Kind (Decl) = Iir_Kind_Interface_Signal_Declaration then
         --  For interfaces, create a pointer so that there is no need to
         --  update a copy if the association is collapsed.
         Info.Signal_Valp := Create_Var
           (Create_Var_Identifier (Decl, "_VALP", 0),
            Get_Object_Ptr_Type (Type_Info, Mode_Value));

         if Get_Default_Value (Decl) /= Null_Iir then
            --  Default value for ports.
            Info.Signal_Val := Create_Var
              (Create_Var_Identifier (Decl, "_INIT", 0),
               Get_Object_Type (Type_Info, Mode_Value));
         end if;
      else
         Info.Signal_Val := Create_Var
           (Create_Var_Identifier (Decl, "_VAL", 0),
            Get_Object_Type (Type_Info, Mode_Value));
      end if;

      case Get_Kind (Decl) is
         when Iir_Kind_Signal_Declaration
            | Iir_Kind_Interface_Signal_Declaration =>
            Rtis.Generate_Signal_Rti (Decl);
         when Iir_Kind_Guard_Signal_Declaration =>
            --  No name created for guard signal.
            null;
         when others =>
            Error_Kind ("create_signal", Decl);
      end case;
   end Create_Signal;

   procedure Create_Implicit_Signal (Decl : Iir)
   is
      Sig_Type_Def : constant Iir := Get_Type (Decl);
      Type_Info    : constant Type_Info_Acc := Get_Info (Sig_Type_Def);
      Info         : Signal_Info_Acc;
   begin
      --  The type of DECL is already known: either bit, or boolean or the
      --  type of the prefix.

      Info := Add_Info (Decl, Kind_Signal);

      Info.Signal_Sig := Create_Var
        (Create_Uniq_Identifier,
         Get_Object_Type (Type_Info, Mode_Signal));
      Info.Signal_Val := Create_Var
        (Create_Uniq_Identifier,
         Get_Object_Type (Type_Info, Mode_Value));
   end Create_Implicit_Signal;

   procedure Create_File_Object (El : Iir_File_Declaration)
   is
      Obj_Type_Def : constant Iir := Get_Type (El);
      Obj_Type     : constant O_Tnode :=
        Get_Ortho_Type (Obj_Type_Def, Mode_Value);
      Info         : Ortho_Info_Acc;
   begin
      Info := Add_Info (El, Kind_Object);

      Info.Object_Var := Create_Var (Create_Var_Identifier (El), Obj_Type);
   end Create_File_Object;

   procedure Create_Package_Interface (Inter : Iir)
   is
      Pkg      : constant Iir := Get_Uninstantiated_Package_Decl (Inter);
      Pkg_Info : constant Ortho_Info_Acc := Get_Info (Pkg);
      Info     : Ortho_Info_Acc;
   begin
      Info := Add_Info (Inter, Kind_Package_Instance);

      --  The spec
      Info.Package_Instance_Spec_Var :=
        Create_Var (Create_Var_Identifier (Inter, "SPEC", 0),
                    Pkg_Info.Package_Spec_Ptr_Type);
      Set_Scope_Via_Var_Ptr
        (Info.Package_Instance_Spec_Scope,
         Info.Package_Instance_Spec_Var);

      --  The body
      Info.Package_Instance_Body_Var :=
        Create_Var (Create_Var_Identifier (Inter, "BODY", 0),
                    Pkg_Info.Package_Body_Ptr_Type);
      Set_Scope_Via_Var_Ptr
        (Info.Package_Instance_Body_Scope,
         Info.Package_Instance_Body_Var);

      Chap2.Instantiate_Info_Package (Inter);
   end Create_Package_Interface;

   procedure Allocate_Complex_Object (Obj_Type   : Iir;
                                      Alloc_Kind : Allocation_Kind;
                                      Var        : in out Mnode)
   is
      Type_Info : constant Type_Info_Acc := Get_Type_Info (Var);
      Kind      : constant Object_Kind_Type := Get_Object_Kind (Var);
   begin
      --  Cannot allocate unconstrained object (since size is unknown).
      pragma Assert (Type_Info.Type_Mode not in Type_Mode_Unbounded);

      if not Is_Complex_Type (Type_Info) then
         --  Object is not complex.
         return;
      end if;

      --  Allocate variable.
      New_Assign_Stmt
        (M2Lp (Var),
         Gen_Alloc (Alloc_Kind,
                    Chap3.Get_Subtype_Size (Obj_Type, Mnode_Null, Kind),
                    Type_Info.Ortho_Ptr_Type (Kind)));
   end Allocate_Complex_Object;

   --  Note : OBJ can be a tree.
   --  FIXME: should use translate_aggregate_others.
   procedure Init_Array_Object (Obj : Mnode; Obj_Type : Iir)
   is
      --  Type of the object.
      Type_Info : constant Type_Info_Acc := Get_Info (Obj_Type);

      Sobj : Mnode;

      --  Iterator for the elements.
      Index : O_Dnode;

      Upper_Limit : O_Enode;
      Upper_Var   : O_Dnode;

      Label : O_Snode;
   begin
      --  Iterate on all elements of the object.
      Open_Temp;

      if Type_Info.Type_Mode = Type_Mode_Unbounded_Array then
         Sobj := Stabilize (Obj);
      else
         Sobj := Obj;
      end if;

      Upper_Limit := Chap3.Get_Array_Length (Sobj, Obj_Type);
      if Type_Info.Type_Mode = Type_Mode_Static_Array then
         Upper_Var := O_Dnode_Null;
      else
         --  Hoist the computation of the limit before the loop.
         Upper_Var := Create_Temp_Init (Ghdl_Index_Type, Upper_Limit);
      end if;

      Index := Create_Temp (Ghdl_Index_Type);
      Init_Var (Index);
      Start_Loop_Stmt (Label);
      if Upper_Var /= O_Dnode_Null then
         Upper_Limit := New_Obj_Value (Upper_Var);
      end if;
      Gen_Exit_When (Label,
                     New_Compare_Op (ON_Eq,
                                     New_Obj_Value (Index), Upper_Limit,
                                     Ghdl_Bool_Type));
      Init_Object
        (Chap6.Translate_Indexed_Name_By_Offset (Sobj, Obj_Type, Index),
         Get_Element_Subtype (Obj_Type));
      Inc_Var (Index);
      Finish_Loop_Stmt (Label);

      Close_Temp;
   end Init_Array_Object;

   procedure Init_Protected_Object (Obj : Mnode; Obj_Type : Iir)
   is
      Info  : constant Type_Info_Acc := Get_Info (Obj_Type);
      Assoc : O_Assoc_List;
   begin
      --  Call the initializer.
      Start_Association (Assoc, Info.B.Prot_Init_Subprg);
      Subprgs.Add_Subprg_Instance_Assoc (Assoc, Info.B.Prot_Init_Instance);
      --  Use of M2Lp is a little bit fragile (not sure we get the
      --  variable, but should work: we didn't stabilize it).
      New_Assign_Stmt (M2Lp (Obj), New_Function_Call (Assoc));
   end Init_Protected_Object;

   procedure Fini_Protected_Object (Decl : Iir)
   is
      Info  : constant Type_Info_Acc := Get_Info (Get_Type (Decl));
      Obj   : Mnode;
      Assoc : O_Assoc_List;
   begin
      Obj := Chap6.Translate_Name (Decl, Mode_Value);
      --  Call the Finalizator.
      Start_Association (Assoc, Info.B.Prot_Final_Subprg);
      New_Association (Assoc, M2E (Obj));
      New_Procedure_Call (Assoc);
   end Fini_Protected_Object;

   function Get_Scalar_Initial_Value (Atype : Iir) return O_Enode
   is
      Tinfo : constant Type_Info_Acc := Get_Info (Atype);
   begin
      case Tinfo.Type_Mode is
         when Type_Mode_Scalar =>
            return Chap14.Translate_Left_Type_Attribute (Atype);
         when Type_Mode_Acc
           | Type_Mode_Bounds_Acc =>
            return New_Lit (New_Null_Access (Tinfo.Ortho_Type (Mode_Value)));
         when others =>
            Error_Kind ("get_scalar_initial_value", Atype);
      end case;
   end Get_Scalar_Initial_Value;

   procedure Init_Object (Obj : Mnode; Obj_Type : Iir)
   is
      Tinfo : constant Type_Info_Acc := Get_Type_Info (Obj);
   begin
      case Tinfo.Type_Mode is
         when Type_Mode_Scalar
           | Type_Mode_Acc
           | Type_Mode_Bounds_Acc =>
            New_Assign_Stmt (M2Lv (Obj), Get_Scalar_Initial_Value (Obj_Type));
         when Type_Mode_Arrays =>
            Init_Array_Object (Obj, Obj_Type);
         when Type_Mode_Records =>
            declare
               List : constant Iir_Flist :=
                 Get_Elements_Declaration_List (Obj_Type);
               Sobj : Mnode;
               El   : Iir_Element_Declaration;
            begin
               Open_Temp;
               Sobj := Stabilize (Obj);
               for I in Flist_First .. Flist_Last (List) loop
                  El := Get_Nth_Element (List, I);
                  Init_Object (Chap6.Translate_Selected_Element (Sobj, El),
                               Get_Type (El));
               end loop;
               Close_Temp;
            end;
         when Type_Mode_Protected =>
            Init_Protected_Object (Obj, Obj_Type);
         when Type_Mode_Unknown
            | Type_Mode_File =>
            raise Internal_Error;
      end case;
   end Init_Object;

   --  Return True iff subtype indication of DECL is a subtype attribute.
   function Is_Object_Type_Attribute (Decl : Iir) return Boolean
   is
      Ind : constant Iir := Get_Subtype_Indication (Decl);
   begin
      return Ind /= Null_Iir
        and then Kind_In (Ind, Iir_Kind_Subtype_Attribute,
                          Iir_Kind_Element_Attribute);
   end Is_Object_Type_Attribute;

   --  Handle 'Subtype or 'Element, return the bounds.
   function Type_Attribute_To_Bounds (Attr : Iir) return Mnode
   is
      Pfx : constant Iir := Get_Prefix (Attr);
      Name : Mnode;
      Bnd : Mnode;
   begin
      if Get_Kind (Pfx) = Iir_Kind_Element_Attribute then
         Bnd := Type_Attribute_To_Bounds (Pfx);
      else
         Name := Chap6.Translate_Name (Pfx, Mode_Value);
         Bnd := Chap3.Get_Composite_Bounds (Name);
      end if;

      case Get_Kind (Attr) is
         when Iir_Kind_Subtype_Attribute =>
            return Bnd;
         when Iir_Kind_Element_Attribute =>
            return Chap3.Array_Bounds_To_Element_Bounds (Bnd, Get_Type (Pfx));
         when others =>
            raise Internal_Error;
      end case;
   end Type_Attribute_To_Bounds;

   procedure Elab_Subtype_Attribute
     (Decl : Iir; Name_Val : Mnode; Name_Sig : Mnode)
   is
      Bnd : Mnode;
   begin
      Bnd := Type_Attribute_To_Bounds (Get_Subtype_Indication (Decl));
      if Name_Sig /= Mnode_Null then
         Stabilize (Bnd);
         New_Assign_Stmt (M2Lp (Chap3.Get_Composite_Bounds (Name_Sig)),
                          M2Addr (Bnd));
      end if;
      New_Assign_Stmt (M2Lp (Chap3.Get_Composite_Bounds (Name_Val)),
                       M2Addr (Bnd));
   end Elab_Subtype_Attribute;

   procedure Elab_Maybe_Type_Attribute
     (Decl : Iir; Name_Val : Mnode; Name_Sig : Mnode) is
   begin
      if not Is_Object_Type_Attribute (Decl) then
         return;
      end if;

      Elab_Subtype_Attribute (Decl, Name_Val, Name_Sig);
   end Elab_Maybe_Type_Attribute;

   --  If SIZE is larger than the threshold, call __ghdl_check_stack_allocation
   --  to raise an error if the size is too large.  There are two threshold:
   --  one set at compile time (Check_Stack_Allocation_Threshold) and one set
   --  at run-time.
   --
   --  Right now, this function is called only for allocation of a complex
   --  object on the stack (constant or variable).  But there are more sources
   --  of stack allocation (temporary aggregate, unbounded objects, individual
   --  assocs...)
   function Maybe_Check_Stack_Allocation (Size : O_Enode) return O_Enode
   is
      Val : O_Dnode;
      If_Blk : O_If_Block;
      Assoc : O_Assoc_List;
   begin
      if Flag_Check_Stack_Allocation = 0 then
         return Size;
      end if;

      Val := Create_Temp_Init (Ghdl_Index_Type, Size);
      Start_If_Stmt
        (If_Blk,
         New_Compare_Op (ON_Ge,
                         New_Obj_Value (Val),
                         New_Lit (Check_Stack_Allocation_Threshold),
                         Ghdl_Bool_Type));
      Start_Association (Assoc, Ghdl_Check_Stack_Allocation);
      New_Association (Assoc, New_Obj_Value (Val));
      New_Procedure_Call (Assoc);
      Finish_If_Stmt (If_Blk);

      return New_Obj_Value (Val);
   end Maybe_Check_Stack_Allocation;

   procedure Elab_Object_Storage (Obj : Iir)
   is
      Obj_Type : constant Iir := Get_Type (Obj);
      Obj_Info : constant Object_Info_Acc := Get_Info (Obj);

      Name_Node : Mnode;

      Type_Info  : Type_Info_Acc;
      Alloc_Kind : Allocation_Kind;
      Size : O_Enode;
   begin
      --  Elaborate subtype.
      case Get_Kind (Obj) is
         when Iir_Kind_Attribute_Value =>
            null;
         when others =>
            if Is_Object_Type_Attribute (Obj) then
               Type_Info := Get_Info (Obj_Type);
               if Type_Info.Type_Mode in Type_Mode_Unbounded then
                  --  Copy bounds and allocate base.
                  Name_Node :=
                    Get_Var (Obj_Info.Object_Var, Type_Info, Mode_Value);
                  Stabilize (Name_Node);
                  Elab_Maybe_Type_Attribute (Obj, Name_Node, Mnode_Null);
                  Alloc_Kind := Get_Alloc_Kind_For_Var (Obj_Info.Object_Var);
                  Chap3.Allocate_Unbounded_Composite_Base
                    (Alloc_Kind, Name_Node, Get_Base_Type (Obj_Type));
               return;
               end if;
            else
               Chap3.Elab_Object_Subtype_Indication (Obj);
            end if;
      end case;

      --  Now the subtype is elaborated, its info is defined.
      Type_Info := Get_Info (Obj_Type);

      --  FIXME: the object type may be a fat array!
      --  FIXME: fat array + aggregate ?

      if Type_Info.Type_Mode = Type_Mode_Protected then
         --  Protected object will be created by its INIT function.
         null;
      elsif Is_Unbounded_Type (Type_Info) then
         --  Allocated during initialization.
         null;
      elsif Is_Complex_Type (Type_Info) then
         --  FIXME: avoid allocation if the value is a string and
         --  the object is a constant
         Name_Node := Get_Var (Obj_Info.Object_Var, Type_Info, Mode_Value);
         Alloc_Kind := Get_Alloc_Kind_For_Var (Obj_Info.Object_Var);
         Size := Chap3.Get_Subtype_Size (Obj_Type, Mnode_Null, Mode_Value);
         if Alloc_Kind = Alloc_Stack then
            Size := Maybe_Check_Stack_Allocation (Size);
         end if;
         --  Was: Allocate_Complex_Object.
         New_Assign_Stmt
           (M2Lp (Name_Node),
            Gen_Alloc (Alloc_Kind,
                       Size,
                       Type_Info.Ortho_Ptr_Type (Mode_Value)));
      end if;
   end Elab_Object_Storage;

   --  Generate code to create object OBJ and initialize it with value VAL.
   procedure Elab_Object_Init
     (Name : Mnode; Obj : Iir; Value : Iir; Alloc_Kind : Allocation_Kind)
   is
      Obj_Type  : constant Iir := Get_Type (Obj);
      Type_Info : constant Type_Info_Acc := Get_Info (Obj_Type);

      Name_Node  : Mnode;
      Value_Node : O_Enode;
   begin
      --  Note: no temporary variable region is created, as the allocation
      --  may be performed on the stack.

      if Value = Null_Iir then
         --  Performs default initialization.
         Open_Temp;
         Init_Object (Name, Obj_Type);
         Close_Temp;
      elsif Get_Kind (Value) = Iir_Kind_Aggregate then
         if Type_Info.Type_Mode in Type_Mode_Unbounded
           and then not Is_Object_Type_Attribute (Obj)
         then
            --  Allocate.
            declare
               Aggr_Type : constant Iir := Get_Type (Value);
               Aggr_Base_Type : constant Iir := Get_Base_Type (Aggr_Type);
            begin
               Name_Node := Stabilize (Name);
               pragma Assert (Get_Object_Kind (Name_Node) = Mode_Value);
               if Get_Constraint_State (Aggr_Type) /= Fully_Constrained then
                  --  Allocate bounds
                  Chap3.Allocate_Unbounded_Composite_Bounds
                    (Alloc_Kind, Name_Node, Aggr_Base_Type);
                  --  Translate bounds
                  Chap7.Translate_Aggregate_Bounds
                    (Stabilize (Chap3.Get_Composite_Bounds (Name_Node)),
                     Value, Mode_Value);
                  --  Allocate base
                  Chap3.Allocate_Unbounded_Composite_Base
                    (Alloc_Kind, Name_Node, Aggr_Base_Type);
               else
                  Chap3.Create_Composite_Subtype (Aggr_Type);
                  if Alloc_Kind = Alloc_Stack then
                     --  Short-cut: don't allocate bounds.
                     New_Assign_Stmt
                       (M2Lp (Chap3.Get_Composite_Bounds (Name_Node)),
                        M2Addr (Chap3.Get_Composite_Type_Bounds (Aggr_Type)));
                     Chap3.Allocate_Unbounded_Composite_Base
                       (Alloc_Kind, Name_Node, Aggr_Base_Type);
                  else
                     Chap3.Translate_Object_Allocation
                       (Name_Node, Alloc_Kind, Aggr_Base_Type,
                        Chap3.Get_Composite_Type_Bounds (Aggr_Type));
                  end if;
               end if;
            end;
         else
            Name_Node := Name;
         end if;
         Chap7.Translate_Aggregate (Name_Node, Obj_Type, Value);
      else
         Value_Node := Chap7.Translate_Expression (Value, Obj_Type);

         if Type_Info.Type_Mode in Type_Mode_Unbounded then
            declare
               S : Mnode;
            begin
               Name_Node := Stabilize (Name);
               S := Stabilize (E2M (Value_Node, Type_Info, Mode_Value));

               if Get_Kind (Value) = Iir_Kind_String_Literal8
                 and then Get_Kind (Obj) = Iir_Kind_Constant_Declaration
               then
                  --  No need to allocate space for the object.
                  Copy_Fat_Pointer (Name_Node, S);
               else
                  Chap3.Translate_Object_Allocation
                    (Name_Node, Alloc_Kind, Obj_Type,
                     Chap3.Get_Composite_Bounds (S));
                  Chap3.Translate_Object_Copy (Name_Node, S, Obj_Type);
               end if;
            end;
         else
            Chap7.Translate_Assign (Name, Value_Node, Value, Obj_Type, Obj);
         end if;
      end if;
   end Elab_Object_Init;

   --  Generate code to create object OBJ and initialize it with value VAL.
   procedure Elab_Object_Value (Obj : Iir; Value : Iir)
   is
      Obj_Info  : constant Object_Info_Acc := Get_Info (Obj);
      Alloc_Kind : constant Allocation_Kind :=
        Get_Alloc_Kind_For_Var (Obj_Info.Object_Var);
      Name : constant Mnode :=
        Get_Var (Obj_Info.Object_Var, Get_Info (Get_Type (Obj)), Mode_Value);
   begin
      Elab_Object_Storage (Obj);
      Elab_Object_Init (Name, Obj, Value, Alloc_Kind);

      if Alloc_Kind = Alloc_Return then
         --  If the object is allocated on the return stack, avoid
         --  deallocation.  Deallocation must be done manually (this concerns
         --  procedures with suspension).
         Disable_Stack2_Release;
      end if;
   end Elab_Object_Value;

   --  Create code to elaborate OBJ.
   procedure Elab_Object (Obj : Iir)
   is
      Value : constant Iir := Get_Default_Value (Obj);
      Obj1  : Iir;
   begin
      --  Set default value.
      if Get_Kind (Obj) = Iir_Kind_Constant_Declaration then
         if Get_Deferred_Declaration_Flag (Obj) then
            --  No code generation for a deferred constant.
            return;
         end if;

         if Get_Kind (Value) = Iir_Kind_Overflow_Literal then
            --  An overflow can be static, but must still generate an error
            --  at run time.
            Chap6.Gen_Bound_Error (Obj);
            return;
         end if;

         if Get_Info (Obj).Object_Static then
            --  A static object is pre-initialized.
            Chap3.Elab_Object_Subtype_Indication (Obj);
            return;
         end if;

         Obj1 := Get_Deferred_Declaration (Obj);
         if Obj1 = Null_Iir then
            Obj1 := Obj;
         end if;
      else
         Obj1 := Obj;
      end if;

      New_Debug_Line_Stmt (Get_Line_Number (Obj));

      --  Still use the default value of the not deferred constant.
      --  FIXME: what about composite types.
      Elab_Object_Value (Obj1, Value);
   end Elab_Object;

   procedure Fini_Object (Obj : Iir)
   is
      Obj_Type  : constant Iir := Get_Type (Obj);
      Type_Info : constant Type_Info_Acc := Get_Info (Obj_Type);
   begin
      case Type_Mode_Valid (Type_Info.Type_Mode) is
         when Type_Mode_Unbounded =>
            declare
               V : Mnode;
            begin
               Open_Temp;
               V := Chap6.Translate_Name (Obj, Mode_Value);
               Stabilize (V);
               Chap3.Gen_Deallocate
                 (New_Value (M2Lp (Chap3.Get_Composite_Bounds (V))));
               Chap3.Gen_Deallocate
                 (New_Value (M2Lp (Chap3.Get_Composite_Base (V))));
               Close_Temp;
            end;
         when Type_Mode_Complex_Array
           | Type_Mode_Complex_Record
           | Type_Mode_Protected =>
            Chap3.Gen_Deallocate
              (New_Value (M2Lp (Chap6.Translate_Name (Obj, Mode_Value))));
         when Type_Mode_Scalar
           | Type_Mode_Static_Record
           | Type_Mode_Static_Array
           | Type_Mode_Acc
           | Type_Mode_Bounds_Acc =>
            null;
         when Type_Mode_File =>
            --  FIXME: free file ?
            null;
      end case;
   end Fini_Object;

   function Get_Nbr_Signals (Sig : Mnode; Sig_Type : Iir) return O_Enode
   is
      Info : constant Type_Info_Acc := Get_Info (Sig_Type);
   begin
      case Info.Type_Mode is
         when Type_Mode_Scalar =>
            --  Note: here we discard SIG...
            return New_Lit (Ghdl_Index_1);
         when Type_Mode_Arrays =>
            declare
               Len    : O_Dnode;
               If_Blk : O_If_Block;
               Ssig   : Mnode;
            begin
               Ssig := Stabilize (Sig);
               Len := Create_Temp_Init
                 (Ghdl_Index_Type,
                  Chap3.Get_Array_Length (Ssig, Sig_Type));
               --  Can dereference the first index only if the array is not a
               --  null array.
               Start_If_Stmt (If_Blk,
                              New_Compare_Op (ON_Neq,
                                              New_Obj_Value (Len),
                                              New_Lit (Ghdl_Index_0),
                                              Ghdl_Bool_Type));
               New_Assign_Stmt
                 (New_Obj (Len),
                  New_Dyadic_Op
                    (ON_Mul_Ov,
                     New_Obj_Value (Len),
                     Get_Nbr_Signals
                       (Chap3.Index_Base
                            (Chap3.Get_Composite_Base (Ssig), Sig_Type,
                             New_Lit (Ghdl_Index_0)),
                        Get_Element_Subtype (Sig_Type))));
               Finish_If_Stmt (If_Blk);

               return New_Obj_Value (Len);
            end;
         when Type_Mode_Records =>
            declare
               List   : constant Iir_Flist :=
                 Get_Elements_Declaration_List (Get_Base_Type (Sig_Type));
               El     : Iir;
               Res    : O_Enode;
               E      : O_Enode;
               Sig_El : Mnode;
               Ssig   : Mnode;
            begin
               Ssig := Stabilize (Sig);
               Res := O_Enode_Null;
               for I in Flist_First .. Flist_Last (List) loop
                  El := Get_Nth_Element (List, I);
                  Sig_El := Chap6.Translate_Selected_Element (Ssig, El);
                  E := Get_Nbr_Signals (Sig_El, Get_Type (El));
                  if Res /= O_Enode_Null then
                     Res := New_Dyadic_Op (ON_Add_Ov, Res, E);
                  else
                     Res := E;
                  end if;
               end loop;
               if Res = O_Enode_Null then
                  --  Empty records.
                  Res := New_Lit (Ghdl_Index_0);
               end if;
               return Res;
            end;
         when Type_Mode_Unknown
            | Type_Mode_File
            | Type_Mode_Acc
            | Type_Mode_Bounds_Acc
            | Type_Mode_Protected =>
            raise Internal_Error;
      end case;
   end Get_Nbr_Signals;

   --  Get the leftest signal of SIG.
   --  The leftest signal of
   --   a scalar signal is itself,
   --   an array signal is the leftest,
   --   a record signal is the first element.
   function Get_Leftest_Signal (Sig: Mnode; Sig_Type : Iir)
                                   return Mnode
   is
      Res      : Mnode;
      Res_Type : Iir;
      Info     : Type_Info_Acc;
   begin
      Res := Sig;
      Res_Type := Sig_Type;
      loop
         Info := Get_Type_Info (Res);
         case Info.Type_Mode is
            when Type_Mode_Scalar =>
               return Res;
            when Type_Mode_Arrays =>
               Res := Chap3.Index_Base
                 (Chap3.Get_Composite_Base (Res), Res_Type,
                  New_Lit (Ghdl_Index_0));
               Res_Type := Get_Element_Subtype (Res_Type);
            when Type_Mode_Records =>
               declare
                  El_List : constant Iir_Flist :=
                    Get_Elements_Declaration_List (Get_Base_Type (Res_Type));
                  Element : constant Iir := Get_Nth_Element (El_List, 0);
               begin
                  Res := Chap6.Translate_Selected_Element (Res, Element);
                  Res_Type := Get_Type (Element);
               end;
            when Type_Mode_Unknown
               | Type_Mode_File
               | Type_Mode_Acc
               | Type_Mode_Bounds_Acc
               | Type_Mode_Protected =>
               raise Internal_Error;
         end case;
      end loop;
   end Get_Leftest_Signal;

   --  Add func and instance.
   procedure Add_Associations_For_Resolver
     (Assoc : in out O_Assoc_List; Func_Decl : Iir)
   is
      Func_Info   : constant Subprg_Info_Acc := Get_Info (Func_Decl);
      Resolv_Info : constant Subprg_Resolv_Info_Acc :=
        Func_Info.Subprg_Resolv;
      Val         : O_Enode;
   begin
      New_Association
        (Assoc, New_Lit (New_Subprogram_Address (Resolv_Info.Resolv_Func,
         Ghdl_Ptr_Type)));
      if Subprgs.Has_Subprg_Instance (Resolv_Info.Var_Instance) then
         Val := New_Convert_Ov
           (Subprgs.Get_Subprg_Instance (Resolv_Info.Var_Instance),
            Ghdl_Ptr_Type);
      else
         Val := New_Lit (New_Null_Access (Ghdl_Ptr_Type));
      end if;
      New_Association (Assoc, Val);
   end Add_Associations_For_Resolver;

   type O_If_Block_Acc is access O_If_Block;

   type Elab_Signal_Data is record
      Value : Mnode;
      --  Default value of the signal.
      Init_Val         : Mnode;
      --  If statement for a block of signals.
      If_Stmt          : O_If_Block_Acc;
      --  True if the default value is set.
      Has_Val          : Boolean;
      --  True if a resolution function was already attached.
      Already_Resolved : Boolean;
      --  True if the signal may already have been created.
      Check_Null       : Boolean;
   end record;

   procedure Elab_Signal_Non_Composite (Targ      : Mnode;
                                        Targ_Type : Iir;
                                        Data      : Elab_Signal_Data)
   is
      Type_Info     : constant Type_Info_Acc := Get_Info (Targ_Type);
      Create_Subprg : O_Dnode;
      Res           : O_Enode;
      Assoc         : O_Assoc_List;
      Init_Val      : O_Enode;
      --  For the resolution function (if any).
      Func          : Iir;
      If_Stmt       : O_If_Block;
      Targ_Ptr      : O_Dnode;
      Value         : Mnode;
   begin
      if Data.Check_Null then
         Targ_Ptr := Create_Temp_Init
           (Ghdl_Signal_Ptr_Ptr,
            New_Unchecked_Address (M2Lv (Targ), Ghdl_Signal_Ptr_Ptr));
         Start_If_Stmt
           (If_Stmt,
            New_Compare_Op (ON_Eq,
                            New_Value (New_Acc_Value (New_Obj (Targ_Ptr))),
                            New_Lit (New_Null_Access (Ghdl_Signal_Ptr)),
                            Ghdl_Bool_Type));
      end if;

      --  Set the value.
      Value := Stabilize (Data.Value);
      if Data.Has_Val then
         Init_Val := M2E (Data.Init_Val);
      else
         Init_Val := Get_Scalar_Initial_Value (Targ_Type);
      end if;
      New_Assign_Stmt (M2Lv (Value), Init_Val);

      --  Create the signal.
      case Type_Mode_Scalar (Type_Info.Type_Mode) is
         when Type_Mode_Scalar (Type_Mode_B1) =>
            Create_Subprg := Ghdl_Create_Signal_B1;
         when Type_Mode_E8 =>
            Create_Subprg := Ghdl_Create_Signal_E8;
         when Type_Mode_E32 =>
            Create_Subprg := Ghdl_Create_Signal_E32;
         when Type_Mode_I32
            | Type_Mode_P32 =>
            Create_Subprg := Ghdl_Create_Signal_I32;
         when Type_Mode_P64
            | Type_Mode_I64 =>
            Create_Subprg := Ghdl_Create_Signal_I64;
         when Type_Mode_F64 =>
            Create_Subprg := Ghdl_Create_Signal_F64;
      end case;

      Start_Association (Assoc, Create_Subprg);
      New_Association
        (Assoc, New_Unchecked_Address (M2Lv (Value), Ghdl_Ptr_Type));

      if Get_Kind (Targ_Type) in Iir_Kinds_Subtype_Definition then
         Func := Has_Resolution_Function (Targ_Type);
      else
         Func := Null_Iir;
      end if;
      if Func /= Null_Iir and then not Data.Already_Resolved then
         Add_Associations_For_Resolver (Assoc, Func);
      else
         New_Association (Assoc, New_Lit (New_Null_Access (Ghdl_Ptr_Type)));
         New_Association (Assoc, New_Lit (New_Null_Access (Ghdl_Ptr_Type)));
      end if;

      Res := New_Function_Call (Assoc);

      if Data.Check_Null then
         New_Assign_Stmt (New_Acc_Value (New_Obj (Targ_Ptr)), Res);
         Finish_If_Stmt (If_Stmt);
      else
         New_Assign_Stmt
           (M2Lv (Targ),
            New_Convert_Ov (Res, Type_Info.Ortho_Type (Mode_Signal)));
      end if;
   end Elab_Signal_Non_Composite;

   function Elab_Signal_Prepare_Composite
     (Targ : Mnode; Targ_Type : Iir; Data : Elab_Signal_Data)
         return Elab_Signal_Data
   is
      Assoc : O_Assoc_List;
      Func  : Iir;
      Res   : Elab_Signal_Data;
   begin
      Res := Data;
      if Get_Kind (Targ_Type) in Iir_Kinds_Subtype_Definition then
         Func := Has_Resolution_Function (Targ_Type);
         if Func /= Null_Iir and then not Data.Already_Resolved then
            if Data.Check_Null then
               Res.If_Stmt := new O_If_Block;
               Start_If_Stmt
                 (Res.If_Stmt.all,
                  New_Compare_Op
                    (ON_Eq,
                     New_Convert_Ov (M2E (Get_Leftest_Signal (Targ,
                                                              Targ_Type)),
                                     Ghdl_Signal_Ptr),
                     New_Lit (New_Null_Access (Ghdl_Signal_Ptr)),
                     Ghdl_Bool_Type));
               --Res.Check_Null := False;
            end if;
            --  Add resolver.
            Start_Association (Assoc, Ghdl_Signal_Create_Resolution);
            Add_Associations_For_Resolver (Assoc, Func);
            New_Association
              (Assoc, New_Convert_Ov (M2Addr (Targ), Ghdl_Ptr_Type));
            New_Association (Assoc, Get_Nbr_Signals (Targ, Targ_Type));
            New_Procedure_Call (Assoc);
            Res.Already_Resolved := True;
         end if;
      end if;
      case Get_Info (Targ_Type).Type_Mode is
         when Type_Mode_Records =>
            Res.Value := Stabilize (Data.Value);
            if Data.Has_Val then
               Res.Init_Val := Stabilize (Data.Init_Val);
            end if;
         when Type_Mode_Arrays =>
            Res.Value := Chap3.Get_Composite_Base (Data.Value);
            if Data.Has_Val then
               Res.Init_Val := Chap3.Get_Composite_Base (Data.Init_Val);
            end if;
         when others =>
            raise Internal_Error;
      end case;
      return Res;
   end Elab_Signal_Prepare_Composite;

   procedure Elab_Signal_Finish_Composite (Data : in out Elab_Signal_Data)
   is
      procedure Free is new Ada.Unchecked_Deallocation
        (Object => O_If_Block, Name => O_If_Block_Acc);
   begin
      if Data.If_Stmt /= null then
         Finish_If_Stmt (Data.If_Stmt.all);
         Free (Data.If_Stmt);
      end if;
   end Elab_Signal_Finish_Composite;

   function Elab_Signal_Update_Array
     (Data : Elab_Signal_Data; Targ_Type : Iir; Index : O_Dnode)
     return Elab_Signal_Data
   is
      N_Init_Val : Mnode;
   begin
      if Data.Has_Val then
         N_Init_Val := Chap3.Index_Base (Data.Init_Val, Targ_Type,
                                         New_Obj_Value (Index));
      else
         N_Init_Val := Mnode_Null;
      end if;
      return Elab_Signal_Data'
        (Value => Chap3.Index_Base (Data.Value, Targ_Type,
                                    New_Obj_Value (Index)),
         Init_Val => N_Init_Val,
         Has_Val => Data.Has_Val,
         If_Stmt => null,
         Already_Resolved => Data.Already_Resolved,
         Check_Null => Data.Check_Null);
   end Elab_Signal_Update_Array;

   function Elab_Signal_Update_Record
     (Data : Elab_Signal_Data; Targ_Type : Iir; El : Iir_Element_Declaration)
     return Elab_Signal_Data
   is
      pragma Unreferenced (Targ_Type);
      N_Init_Val : Mnode;
   begin
      if Data.Has_Val then
         N_Init_Val := Chap6.Translate_Selected_Element (Data.Init_Val, El);
      else
         N_Init_Val := Mnode_Null;
      end if;
      return Elab_Signal_Data'
        (Value => Chap6.Translate_Selected_Element (Data.Value, El),
         Init_Val => N_Init_Val,
         Has_Val => Data.Has_Val,
         If_Stmt => null,
         Already_Resolved => Data.Already_Resolved,
         Check_Null => Data.Check_Null);
   end Elab_Signal_Update_Record;

   procedure Elab_Signal is new Foreach_Non_Composite
     (Data_Type => Elab_Signal_Data,
      Composite_Data_Type => Elab_Signal_Data,
      Do_Non_Composite => Elab_Signal_Non_Composite,
      Prepare_Data_Array => Elab_Signal_Prepare_Composite,
      Update_Data_Array => Elab_Signal_Update_Array,
      Finish_Data_Array => Elab_Signal_Finish_Composite,
      Prepare_Data_Record => Elab_Signal_Prepare_Composite,
      Update_Data_Record => Elab_Signal_Update_Record,
      Finish_Data_Record => Elab_Signal_Finish_Composite);

   --  Elaborate signal subtypes and allocate the storage for the object.
   procedure Elab_Signal_Declaration_Storage (Decl : Iir; Has_Copy : Boolean)
   is
      Is_Port : constant Boolean :=
        Get_Kind (Decl) = Iir_Kind_Interface_Signal_Declaration;
      Sig_Type  : constant Iir := Get_Type (Decl);
      Type_Info : Type_Info_Acc;
      Name_Sig : Mnode;
      Name_Val : Mnode;
   begin
      New_Debug_Line_Stmt (Get_Line_Number (Decl));

      Open_Temp;

      Chap3.Elab_Object_Subtype_Indication (Decl);

      Type_Info := Get_Info (Sig_Type);

      if Type_Info.Type_Mode in Type_Mode_Unbounded then
         --  Allocate storage.
         if Has_Copy then
            Name_Sig := Chap6.Translate_Name (Decl, Mode_Signal);
            Name_Val := Mnode_Null;
         else
            Chap6.Translate_Signal_Name (Decl, Name_Sig, Name_Val);
         end if;

         Name_Sig := Stabilize (Name_Sig);

         if Name_Val /= Mnode_Null then
            Name_Val := Stabilize (Name_Val);
            Elab_Maybe_Type_Attribute (Decl, Name_Val, Name_Sig);
            Chap3.Allocate_Unbounded_Composite_Base
              (Alloc_System, Name_Val, Sig_Type);
         else
            Elab_Maybe_Type_Attribute (Decl, Name_Sig, Mnode_Null);
         end if;

         Chap3.Allocate_Unbounded_Composite_Base
           (Alloc_System, Name_Sig, Sig_Type);

         if Is_Port and then Get_Default_Value (Decl) /= Null_Iir then
            Name_Val := Chap6.Get_Port_Init_Value (Decl);
            Name_Val := Stabilize (Name_Val);
            Chap3.Allocate_Unbounded_Composite_Base
              (Alloc_System, Name_Val, Sig_Type);
         end if;
      elsif Is_Complex_Type (Type_Info) then
         if Has_Copy then
            Name_Sig := Chap6.Translate_Name (Decl, Mode_Signal);
            Name_Val := Mnode_Null;
         else
            Chap6.Translate_Signal_Name (Decl, Name_Sig, Name_Val);
         end if;
         Allocate_Complex_Object (Sig_Type, Alloc_System, Name_Sig);
         if Name_Val /= Mnode_Null then
            Allocate_Complex_Object (Sig_Type, Alloc_System, Name_Val);
         end if;
         if Is_Port and then Get_Default_Value (Decl) /= Null_Iir then
            Name_Val := Chap6.Get_Port_Init_Value (Decl);
            Allocate_Complex_Object (Sig_Type, Alloc_System, Name_Val);
         end if;
      elsif Is_Port then
         if not Has_Copy then
            --  A port that isn't collapsed.  Allocate value.
            Name_Val := Chap6.Translate_Name (Decl, Mode_Value);
            New_Assign_Stmt
              (M2Lp (Name_Val),
               Gen_Alloc (Alloc_System,
                          Chap3.Get_Object_Size (Name_Val, Sig_Type),
                          Type_Info.Ortho_Ptr_Type (Mode_Value)));
         end if;
      end if;

      Close_Temp;
   end Elab_Signal_Declaration_Storage;

   function Has_Direct_Driver (Sig : Iir) return Boolean
   is
      Info : constant Ortho_Info_Acc := Get_Info (Get_Object_Prefix (Sig));
   begin
      --  Can be an alias ?
      return Info.Kind = Kind_Signal
        and then Info.Signal_Driver /= Null_Var;
   end Has_Direct_Driver;

   procedure Elab_Direct_Driver_Declaration_Storage (Decl : Iir)
   is
      Sig_Type  : constant Iir := Get_Type (Decl);
      Sig_Info  : constant Ortho_Info_Acc := Get_Info (Decl);
      Type_Info : constant Type_Info_Acc := Get_Info (Sig_Type);
      Name_Node : Mnode;
   begin
      Open_Temp;

      if Type_Info.Type_Mode in Type_Mode_Unbounded then
         Name_Node := Get_Var (Sig_Info.Signal_Driver, Type_Info, Mode_Value);
         Name_Node := Stabilize (Name_Node);
         --  Copy bounds from signal.
         New_Assign_Stmt
           (M2Lp (Chap3.Get_Composite_Bounds (Name_Node)),
            M2Addr (Chap3.Get_Composite_Bounds
                      (Chap6.Translate_Name (Decl, Mode_Signal))));
         --  Allocate base.
         Chap3.Allocate_Unbounded_Composite_Base
           (Alloc_System, Name_Node, Sig_Type);
      elsif Is_Complex_Type (Type_Info) then
         Name_Node := Get_Var (Sig_Info.Signal_Driver, Type_Info, Mode_Value);
         Allocate_Complex_Object (Sig_Type, Alloc_System, Name_Node);
      end if;

      Close_Temp;
   end Elab_Direct_Driver_Declaration_Storage;

   --  Create signal object.
   --  Note: SIG can be a signal sub-element (used when signals are
   --   collapsed).
   --  If CHECK_NULL is TRUE, create the signal only if it was not yet
   --  created.
   procedure Elab_Signal_Declaration_Object
     (Sig : Iir; Parent : Iir; Check_Null : Boolean)
   is
      Decl      : constant Iir := Strip_Denoting_Name (Sig);
      Sig_Type  : constant Iir := Get_Type (Sig);
      Base_Decl : constant Iir := Get_Object_Prefix (Sig);
      Val_Type  : Iir;
      Name_Sig  : Mnode;
      Name_Val  : Mnode;
      Value     : Iir;
      Data      : Elab_Signal_Data;
   begin
      New_Debug_Line_Stmt (Get_Line_Number (Sig));

      Open_Temp;

      --  Set the name of the signal.
      declare
         Assoc : O_Assoc_List;
      begin
         Start_Association (Assoc, Ghdl_Signal_Name_Rti);
         New_Association
           (Assoc,
            New_Unchecked_Address (New_Obj (Get_Info (Base_Decl).Signal_Rti),
                                   Rtis.Ghdl_Rti_Access));
         Rtis.Associate_Rti_Context (Assoc, Parent);
         New_Procedure_Call (Assoc);
      end;

      Chap6.Translate_Signal_Name (Decl, Name_Sig, Name_Val);
      --  Consistency check: a signal name is a signal.
      pragma Assert (Get_Object_Kind (Name_Sig) = Mode_Signal);

      Data.Value := Name_Val;
      if Decl = Base_Decl then
         Data.Already_Resolved := False;
         Data.Check_Null := Check_Null;
         Value := Get_Default_Value (Base_Decl);
         if Value = Null_Iir then
            Data.Has_Val := False;
         else
            Data.Has_Val := True;
            Val_Type := Get_Type (Value);

            if Get_Kind (Value) = Iir_Kind_Aggregate
              and then Get_Constraint_State (Sig_Type) /= Fully_Constrained
              and then Get_Constraint_State (Val_Type) /= Fully_Constrained
            then
               --  Both the signal type and the value type are not fully
               --  constrained.  This can happend when the signal subtype
               --  indication is 'subtype and the default value is an
               --  aggregate.  The signal was created with bounds, so use
               --  those bounds.
               declare
                  Tinfo : constant Type_Info_Acc := Get_Info (Sig_Type);
                  V : Mnode;
               begin
                  Stabilize (Data.Value);
                  V := Create_Temp (Tinfo);
                  New_Assign_Stmt
                    (M2Lp (Chap3.Get_Composite_Bounds (V)),
                     M2Addr (Chap3.Get_Composite_Bounds (Data.Value)));
                  pragma Assert (Val_Type = Sig_Type);
                  Chap3.Allocate_Unbounded_Composite_Base
                    (Alloc_Stack, V, Sig_Type);
                  Chap7.Translate_Aggregate (V, Val_Type, Value);
                  Data.Init_Val := V;
               end;
            else
               Data.Init_Val := Chap7.Translate_Expression (Value, Sig_Type);
            end if;
         end if;
      else
         --  Sub signal.
         --  Do not add resolver.
         --  Do not use default value.
         Data.Already_Resolved := True;
         Data.Has_Val := False;
         Data.Check_Null := False;
         Value := Null_Iir;
      end if;
      Elab_Signal (Name_Sig, Sig_Type, Data);

      Close_Temp;

      if Value /= Null_Iir then
         Chap9.Destroy_Types (Value);
      end if;
   end Elab_Signal_Declaration_Object;

   procedure Elab_Signal_Declaration
     (Decl : Iir; Parent : Iir; Check_Null : Boolean)
   is
   begin
      Elab_Signal_Declaration_Storage (Decl, False);
      Elab_Signal_Declaration_Object (Decl, Parent, Check_Null);
   end Elab_Signal_Declaration;

   procedure Elab_Signal_Attribute (Decl : Iir)
   is
      Info        : constant Signal_Info_Acc := Get_Info (Decl);
      Dtype       : constant Iir := Get_Type (Decl);