summaryrefslogtreecommitdiff
path: root/src/vlog2Spice.c
blob: 5b70297b95692b9d387d92c3eb514a5067b77f00 (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
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
//--------------------------------------------------------------
// vlog2Spice
//
// Convert a structural verilog netlist (with power and ground
// nets!) into a SPICE netlist.
//
// Revision 0, 2006-11-11: First release by R. Timothy Edwards.
// Revision 1, 2009-07-13: Minor cleanups by Philipp Klaus Krause.
// Revision 2, 2013-05-10: Modified to take a library of subcell
//		definitions to use for determining port order.
// Revision 3, 2013-10-09: Changed from BDnet2BSpice to
//		blif2BSpice
// Revision 4, 2018-11-28: Changed from blif2BSpice to vlog2Spice
//
//--------------------------------------------------------------

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <math.h>
#include <ctype.h>
#include <float.h>

#include "hash.h"
#include "readverilog.h"

#define LengthOfLine    	16384

#define DO_INCLUDE   0x01
#define DO_DELIMITER 0x02

/* Linked list of names of SPICE libraries to read */
typedef struct _linkedstring *LinkedStringPtr;

typedef struct _linkedstring {
    char *string;
    LinkedStringPtr next;
} LinkedString;

/* Function prototypes */
int write_output(struct cellrec *, LinkedStringPtr, char *, int);
int loc_getline(char s[], int lim, FILE *fp);
void helpmessage(FILE *);

//--------------------------------------------------------

int main (int argc, char *argv[])
{
    int i, result = 0;
    int flags = 0;
    char *eptr;

    char *vloginname = NULL;
    char *spclibname = NULL;
    char *spcoutname = NULL;

    LinkedStringPtr spicelibs = NULL, newspicelib;


    struct cellrec *topcell = NULL;

    while ((i = getopt(argc, argv, "hHidD:l:s:o:")) != EOF) {
	switch (i) {
	    case 'l':
		newspicelib = (LinkedStringPtr)malloc(sizeof(LinkedString));
		newspicelib->string = strdup(optarg);
		newspicelib->next = spicelibs;
		spicelibs = newspicelib;
		break;
	    case 'o':
		spcoutname = strdup(optarg);
		break;
	    case 'i':
		flags |= DO_INCLUDE;
		break;
	    case 'd':
		flags |= DO_DELIMITER;
		break;
	    case 'h':
	    case 'H':
		helpmessage(stdout);
		exit(0);
		break;
	    case 'D':
		eptr = strchr(optarg, '=');
		if (eptr != NULL) {
		    *eptr = '\0';
		    VerilogDefine(optarg, eptr + 1);
		    *eptr = '=';
		}
		else
		    VerilogDefine(optarg, "1");
		break;
	    default:
		fprintf(stderr, "Unknown switch %c\n", (char)i);
		helpmessage(stderr);
		exit(1);
		break;
	}
    }

    if (optind < argc) {
	vloginname = strdup(argv[optind]);
	optind++;
    }
    else {
	fprintf(stderr, "Couldn't find a filename as input\n");
	helpmessage(stderr);
	exit(1);
    }
    optind++;

    topcell = ReadVerilog(vloginname);
    if (topcell != NULL)
	result = write_output(topcell, spicelibs, spcoutname, flags);
    else
	result = 1;	/* Return error code */

    return result;
}

/*--------------------------------------------------------------*/
/* Verilog backslash notation, which is the most absurd syntax	*/
/* in the known universe, is fundamentally incompatible with	*/
/* SPICE.  The ad-hoc solution used by qflow is to replace	*/
/* the trailing space with another backslash such that the	*/
/* name is SPICE-compatible and the original syntax can be	*/
/* recovered when needed.					*/
/*--------------------------------------------------------------*/

void backslash_fix(char *netname)
{
    char *sptr;

    if (*netname == '\\')
	if ((sptr = strchr(netname, ' ')) != NULL)
	    *sptr = '\\';
}

/*--------------------------------------------------------------*/
/* write_output ---  Write the SPICE netlist output		*/
/*								*/
/* ARGS: 							*/
/* RETURNS: 0 on success, 1 on error.				*/
/* SIDE EFFECTS: 						*/
/*--------------------------------------------------------------*/

int write_output(struct cellrec *topcell, LinkedStringPtr spicelibs,
		char *outname, int flags)
{
    FILE *libfile;
    FILE *outfile;
    char *libname;
    LinkedStringPtr curspicelib;

    struct netrec *net;
    struct instance *inst;
    struct portrec *port;
    struct portrec *newport, *portlist, *lastport;

    int i, j, k, start, end, pcount = 1;
    int result = 0;
    int instidx, insti;

    char *lptr;
    char *sp, *sp2;
    char line[LengthOfLine];

    struct hashtable Libhash;

    if (outname != NULL) {
	outfile = fopen(outname, "w");
	if (outfile == NULL) {
	    fprintf(stderr, "Error:  Couldn't open file %s for writing\n", outname);
	    return 1;
	}
    }
    else
	outfile = stdout;

    /* Initialize SPICE library hash table */
    InitializeHashTable(&Libhash, SMALLHASHSIZE);

    // Read one or more SPICE libraries of subcircuits and use them to define
    // the order of pins that were read from LEF (which is not necessarily in
    // SPICE pin order).

    for (curspicelib = spicelibs; curspicelib; curspicelib = curspicelib->next) {
	libname = curspicelib->string;

	libfile = fopen(libname, "r");
	if (libfile == NULL) {
	    fprintf(stderr, "Couldn't open %s for reading\n", libname);
	    continue;
	}

	/* Read SPICE library of subcircuits, if one is specified.	*/
	/* Retain the name and order of ports passed to each		*/
	/* subcircuit.							*/

	j = 0;
	while (loc_getline(line, sizeof(line), libfile) > 0) {
	    if (!strncasecmp(line, ".subckt", 7)) {
		char *cellname;
		lastport = NULL;
		portlist = NULL;

		/* Read cellname */
		sp = line + 7;
		while (isspace(*sp) && (*sp != '\n')) sp++;
		sp2 = sp;
		while (!isspace(*sp2) && (*sp2 != '\n')) sp2++;
		*sp2 = '\0';

		/* Keep a record of the cellname until we generate the	*/
		/* hash entry for it					*/
		cellname = strdup(sp);

		/* Now fill out the ordered port list */
		sp = sp2 + 1;
		while (isspace(*sp) && (*sp != '\n') && (*sp != '\0')) sp++;
		while (sp) {

		    /* Move string pointer to next port name */

		    if (*sp == '\n' || *sp == '\0') {
			loc_getline(line, sizeof(line), libfile);
			if (*line == '+')
			    sp = line + 1;
			else
			    break;
		    }
		    while (isspace(*sp) && (*sp != '\n')) sp++;

		    /* Terminate port name and advance pointer */
		    sp2 = sp;
		    while (!isspace(*sp2) && (*sp2 != '\n') && (*sp2 != '\0')) sp2++;
		    *sp2 = '\0';

		    /* Add port to list (in forward order) */

		    newport = (struct portrec *)malloc(sizeof(struct portrec));
		    if (portlist == NULL)
			portlist = newport;
		    else
			lastport->next = newport;
		    lastport = newport;
		    newport->name = strdup(sp);
		    newport->net = NULL;
		    newport->direction = 0;
		    newport->next = NULL;

		    sp = sp2 + 1;
		}

		/* Read input to end of subcircuit */

		if (strncasecmp(line, ".ends", 4)) {
		    while (loc_getline(line, sizeof(line), libfile) > 0)
			if (!strncasecmp(line, ".ends", 4))
			    break;
		}

		/* Hash the new port record by cellname */
		HashPtrInstall(cellname, portlist, &Libhash);
		free(cellname);
	    }
	}
	fclose(libfile);
    }

    /* Write output header */
    fprintf(outfile, "*SPICE netlist created from verilog structural netlist module "
			"%s by vlog2Spice (qflow)\n", topcell->name);
    fprintf(outfile, "*This file may contain array delimiters, not for use in simulation.\n");
    fprintf(outfile, "\n");

    /* If flags has DO_INCLUDE then dump the contents of the	*/
    /* libraries.  If 0, then just write a .include line.	*/

    for (curspicelib = spicelibs; curspicelib; curspicelib = curspicelib->next) {
	libname = curspicelib->string;

	if (flags & DO_INCLUDE) {
	    libfile = fopen(libname, "r");
	    if (libname != NULL) {
		fprintf(outfile, "** Start of included library %s\n", libname);
		/* Write out the subcircuit library file verbatim */
		while (loc_getline(line, sizeof(line), libfile) > 0)
		    fputs(line, outfile);
		fprintf(outfile, "** End of included library %s\n", libname);
		fclose(libfile);
	    }
	}
	else {
	    fprintf(outfile, ".include %s\n", libname);
	}
    }
    fprintf(outfile, "\n");

    /* Generate the subcircuit definition, adding power and ground nets */

    fprintf(outfile, ".subckt %s ", topcell->name);

    for (port = topcell->portlist; port; port = port->next) {
	if ((net = BusHashLookup(port->name, &topcell->nets)) != NULL) {
	    start = net->start;
	    end = net->end;
	}
	else start = end = -1;

	if (start > end) {
	    int tmp;
	    tmp = start;
	    start = end;
	    end = tmp;
	}
	if (start == end) {
	    fprintf(outfile, "%s", port->name);
	    if (pcount++ % 8 == 7) {
		pcount = 0;
		fprintf(outfile, "\n+");
	    }
	    fprintf(outfile, " ");
	}
	else {
	    for (i = start; i <= end; i++) {
		/* Note that use of brackets is not legal SPICE syntax	*/
		/* but suffices for LVS and such.  Output should be	*/
		/* post-processed before using in simulation.		*/
		if (flags & DO_DELIMITER)
		    fprintf(outfile, "%s<%d>", port->name, i);
		else
		    fprintf(outfile, "%s[%d]", port->name, i);

		if (pcount++ % 8 == 7) {
		    pcount = 0;
		    fprintf(outfile, "\n+");
		}
		fprintf(outfile, " ");
	    }
	}
    }
    fprintf(outfile, "\n\n");

    /* Output instances */

    instidx = -1;
    for (inst = topcell->instlist; inst; ) {
	int argcnt;
	struct portrec *libport;

	/* Check if the instance is an array */
	if (inst->arraystart != -1) {
	    if (instidx == -1) {
		instidx = inst->arraystart;
		insti = 0;
	    }
	    else if (inst->arraystart > inst->arrayend) {
		instidx--;
		insti++;
	    }
	    else if (inst->arraystart < inst->arrayend) {
		instidx++;
		insti++;
	    }
	}

	if (inst->arraystart == -1)
	    fprintf(outfile, "X%s ", inst->instname);
	else
	    fprintf(outfile, "X%s[%d] ", inst->instname, instidx);
        pcount = 1;

	/* Search library records for subcircuit */

	portlist = (struct portrec *)HashLookup(inst->cellname, &Libhash);

	/* If no library entry exists, complain about arbitrary port	*/
	/* order, then use the instance's port names to create a port	*/
	/* record entry.						*/

	if (portlist == NULL) {
	    fprintf(stderr, "Warning:  No SPICE subcircuit for %s.  Pin"
			" order will be arbitrary.\n", inst->cellname);
	    lastport = portlist = NULL;
	    for (libport = inst->portlist; libport; libport = libport->next) {
	    	newport = (struct portrec *)malloc(sizeof(struct portrec));
		if (portlist == NULL)
			portlist = newport;
		else
		    lastport->next = newport;
		lastport = newport;
		newport->name = strdup(libport->name);
		newport->net = NULL;
		newport->direction = libport->direction;
		newport->next = NULL;
	    }
	    HashPtrInstall(inst->cellname, portlist, &Libhash);
	}

	/* Output pin connections in the order of the LEF record, which	*/
	/* has been forced to match the port order of the SPICE library	*/
	/* If there is no SPICE library record, output in the order of	*/
	/* the instance, which may or may not be correct.  In such a	*/
	/* case, flag a warning.					*/

	argcnt = 0;
	for (libport = portlist; ; libport = libport->next) {
	    char *dptr, dsave;
	    int idx = 0, is_array = FALSE, match = FALSE;

	    if (portlist != NULL && libport == NULL) break;

	    argcnt++;
	    argcnt %= 8;
	    if (argcnt == 7)
		fprintf(outfile, "\n+ ");

	    dptr = NULL;
	    if (libport) {
		for (dptr = libport->name; *dptr != '\0'; dptr++) {
		    if (*dptr == '[') {
			is_array = TRUE;
			dsave = *dptr;
			*dptr = '\0';
			sscanf(dptr + 1, "%d", &idx);
			break;
		    }
		}
	    }

	    /* Treat arrayed instances like a bit-blasted port */
	    if ((is_array == FALSE) && (inst->arraystart != -1)) {
		is_array = TRUE;
		idx = insti;
	    } 

	    for (port = inst->portlist; port; port = port->next) {
		/* Find the port name in the instance which matches */
		/* the port name in the macro definition.	    */

		if (libport) {
		    if (!strcasecmp(libport->name, port->name)) {
			match = TRUE;
			break;
		    }
		}
		else {
		    match = TRUE;
		    break;
		}
	    }
	    if (!match) {
		char *gptr;

		/* Deal with annoying use of "!" as a global indicator,	*/
		/* which is sometimes used. . .				*/
		gptr = libport->name + strlen(libport->name) - 1;
		if (*gptr == '!') {
		    *gptr = '\0';
		    for (port = inst->portlist; port; port = port->next) {
			if (!strcasecmp(libport->name, port->name)) {
			    match = TRUE;
			    break;
			}
		    }
		    *gptr = '!';
		}
		else {
		    for (port = inst->portlist; port; port = port->next) {
			gptr = port->name + strlen(port->name) - 1;
			if (*gptr == '!') {
			    *gptr = '\0';
			    if (!strcasecmp(libport->name, port->name)) match = TRUE;
			    *gptr = '!';
			    if (match == TRUE) break;
			}
		    }
		}
	    }
	    if (!match) {
		fprintf(stderr, "Error:  Instance %s has no port %s!\n",
			inst->instname, libport->name);
	    }
	    else {
		if (flags & DO_DELIMITER) {
		    char *d1ptr, *d2ptr;
		    if ((d1ptr = strchr(port->net, '[')) != NULL) {
			if ((d2ptr = strchr(d1ptr + 1, ']')) != NULL) {
			    *d1ptr = '<';
			    *d2ptr = '>';
			}
		    }
		}
		if (is_array) {
		    char *portname = port->net;
		    if (*portname == '{') {
			char *epos, ssave;
			int k;

			/* Bus notation "{a, b, c, ... }"	    */
			/* Go to the end and count bits backwards.  */
			/* until reaching the idx'th position.	    */

			/* To be done:  Move GetIndexedNet() from   */
			/* vlog2Verilog.c to readverilog.c and call */
			/* it from here.  It is more complete than  */
			/* this implementation.			    */

			while (*portname != '}' && *portname != '\0') portname++;
			for (k = 0; k < idx; k++) {
			    epos = portname;
			    portname--;
			    while (*portname != ',' && portname > port->net)
				portname--;
			}
			if (*portname == ',') portname++;
			ssave = *epos;
			*epos = '\0';
			backslash_fix(portname);
			fprintf(outfile, "%s", portname);
			*epos = ssave;
		    }
		    else {
			struct netrec wb;

			GetBus(portname, &wb, &topcell->nets);

			if (wb.start < 0) {
			    /* portname is not a bus */
			    backslash_fix(portname);
			    fprintf(outfile, "%s", portname);
			}
			else {
			    int lidx;
			    if (wb.start < wb.end)
				lidx =  wb.start + idx;
			    else
				lidx = wb.start - idx;
			    /* portname is a partial or full bus */
			    dptr = strrchr(portname, '[');
			    if (dptr) *dptr = '\0';
			    backslash_fix(portname);
			    if (flags & DO_DELIMITER)
				fprintf(outfile, "%s<%d>", portname, lidx);
			    else
				fprintf(outfile, "%s[%d]", portname, lidx);
			    if (dptr) *dptr = '[';
			}
		    }
		}
		else {
		    backslash_fix(port->net);
		    fprintf(outfile, "%s", port->net);
		}

		if (pcount++ % 8 == 7) {
		    pcount = 0;
		    fprintf(outfile, "\n+");
		}
		fprintf(outfile, " ");
	    }

	    if (portlist == NULL) {
		fprintf(stdout, "Warning:  No defined subcircuit %s for "
				"instance %s!\n", inst->cellname, inst->instname);
		fprintf(stdout, "Pins will be output in arbitrary order.\n");
		break;
	    }
	    if (dptr != NULL) *dptr = '[';
	}
	fprintf(outfile, "%s\n", inst->cellname);

	if ((inst->arraystart != -1) && (instidx != inst->arrayend)) continue;
	instidx = -1;
	inst = inst->next;
    }
    fprintf(outfile, "\n.ends\n");
    fprintf(outfile, ".end\n");

    if (outname != NULL) fclose(outfile);

    return result;
}

/*--------------------------------------------------------------*/
/*C loc_getline: read a line, return length			*/
/*								*/
/* ARGS: 							*/
/* RETURNS: 1 to OS						*/
/* SIDE EFFECTS: 						*/
/*--------------------------------------------------------------*/

int loc_getline(char *s, int lim, FILE *fp)
{
    int c, i;
	
    i = 0;
    while(--lim > 0 && (c = getc(fp)) != EOF && c != '\n')
	s[i++] = c;
    if (c == '\n')
	s[i++] = c;
    s[i] = '\0';
    if (c == EOF) i = 0; 
    return i;
}

/*--------------------------------------------------------------*/
/*C helpmessage - tell user how to use the program		*/
/*								*/
/*  ARGS: error code (0 = success, 1 = error)			*/
/*  RETURNS: 1 to OS						*/
/*  SIDE EFFECTS: 						*/
/*--------------------------------------------------------------*/

void helpmessage(FILE *fout)
{
    fprintf(fout, "vlog2Spice [-options] netlist \n");
    fprintf(fout, "\n");
    fprintf(fout, "vlog2Spice converts a netlist in verilog format \n");
    fprintf(fout, "to Spice subcircuit format. Output on stdout unless -o option used.\n");
    fprintf(fout, "Input file must be a structural verilog netlist with power and ground.\n");
    fprintf(fout, "\n");
    fprintf(fout, "Options:\n");
    fprintf(fout, "   -h          Print this message\n");    
    fprintf(fout, "   -i          Generate include statement for library, not a dump.\n");
    fprintf(fout, "   -d          Convert array delimiter brackets to angle brackets.\n");
    fprintf(fout, "   -D <key>=<value>  Preregister a verilog definition.\n");
    fprintf(fout, "   -l <path>   Specify path to SPICE library of standard cells.\n");
    fprintf(fout, "   -o <path>   Specify path to output SPICE file.\n");
    fprintf(fout, "\n");

} /* helpmessage() */