]> git.sur5r.net Git - cc65/blob - src/cc65/main.c
Added a peephole optimization step for global array accesses
[cc65] / src / cc65 / main.c
1 /*****************************************************************************/
2 /*                                                                           */
3 /*                                  main.c                                   */
4 /*                                                                           */
5 /*                             cc65 main program                             */
6 /*                                                                           */
7 /*                                                                           */
8 /*                                                                           */
9 /* (C) 2000-2001 Ullrich von Bassewitz                                       */
10 /*               Wacholderweg 14                                             */
11 /*               D-70597 Stuttgart                                           */
12 /* EMail:        uz@cc65.org                                                 */
13 /*                                                                           */
14 /*                                                                           */
15 /* This software is provided 'as-is', without any expressed or implied       */
16 /* warranty.  In no event will the authors be held liable for any damages    */
17 /* arising from the use of this software.                                    */
18 /*                                                                           */
19 /* Permission is granted to anyone to use this software for any purpose,     */
20 /* including commercial applications, and to alter it and redistribute it    */
21 /* freely, subject to the following restrictions:                            */
22 /*                                                                           */
23 /* 1. The origin of this software must not be misrepresented; you must not   */
24 /*    claim that you wrote the original software. If you use this software   */
25 /*    in a product, an acknowledgment in the product documentation would be  */
26 /*    appreciated but is not required.                                       */
27 /* 2. Altered source versions must be plainly marked as such, and must not   */
28 /*    be misrepresented as being the original software.                      */
29 /* 3. This notice may not be removed or altered from any source              */
30 /*    distribution.                                                          */
31 /*                                                                           */
32 /*****************************************************************************/
33
34
35
36 #include <stdio.h>
37 #include <string.h>
38 #include <stdlib.h>
39 #include <errno.h>
40
41 /* common */
42 #include "abend.h"
43 #include "chartype.h"
44 #include "cmdline.h"
45 #include "fname.h"
46 #include "print.h"
47 #include "target.h"
48 #include "tgttrans.h"
49 #include "version.h"
50 #include "xmalloc.h"
51
52 /* cc65 */
53 #include "asmcode.h"
54 #include "compile.h"
55 #include "codeopt.h"
56 #include "cpu.h"
57 #include "error.h"
58 #include "global.h"
59 #include "incpath.h"
60 #include "input.h"
61 #include "macrotab.h"
62 #include "scanner.h"
63 #include "segments.h"
64
65
66
67 /*****************************************************************************/
68 /*                                   Code                                    */
69 /*****************************************************************************/
70
71
72
73 static void Usage (void)
74 {
75     fprintf (stderr,
76              "Usage: %s [options] file\n"
77              "Short options:\n"
78              "  -d\t\t\tDebug mode\n"
79              "  -g\t\t\tAdd debug info to object file\n"
80              "  -h\t\t\tHelp (this text)\n"
81              "  -j\t\t\tDefault characters are signed\n"
82              "  -o name\t\tName the output file\n"
83              "  -t sys\t\tSet the target system\n"
84              "  -v\t\t\tIncrease verbosity\n"
85              "  -A\t\t\tStrict ANSI mode\n"
86              "  -Cl\t\t\tMake local variables static\n"
87              "  -Dsym[=defn]\t\tDefine a symbol\n"
88              "  -I dir\t\tSet an include directory search path\n"
89              "  -O\t\t\tOptimize code\n"
90              "  -Oi\t\t\tOptimize code, inline more code\n"
91              "  -Or\t\t\tEnable register variables\n"
92              "  -Os\t\t\tInline some known functions\n"
93              "  -T\t\t\tInclude source as comment\n"
94              "  -V\t\t\tPrint the compiler version number\n"
95              "  -W\t\t\tSuppress warnings\n"
96              "\n"
97              "Long options:\n"
98              "  --ansi\t\tStrict ANSI mode\n"
99              "  --bss-name seg\tSet the name of the BSS segment\n"
100              "  --check-stack\t\tGenerate stack overflow checks\n"
101              "  --code-name seg\tSet the name of the CODE segment\n"
102              "  --codesize x\t\tAccept larger code by factor x\n"
103              "  --cpu type\t\tSet cpu type\n"
104              "  --data-name seg\tSet the name of the DATA segment\n"
105              "  --debug\t\tDebug mode\n"
106              "  --debug-info\t\tAdd debug info to object file\n"
107              "  --debug-opt name\tDebug optimization steps\n"
108              "  --disable-opt name\tDisable an optimization step\n"
109              "  --enable-opt name\tEnable an optimization step\n"
110              "  --help\t\tHelp (this text)\n"
111              "  --include-dir dir\tSet an include directory search path\n"
112              "  --list-opt-steps\tList all optimizer steps and exit\n"
113              "  --rodata-name seg\tSet the name of the RODATA segment\n"
114              "  --signed-chars\tDefault characters are signed\n"
115              "  --static-locals\tMake local variables static\n"
116              "  --target sys\t\tSet the target system\n"
117              "  --verbose\t\tIncrease verbosity\n"
118              "  --version\t\tPrint the compiler version number\n",
119              ProgName);
120 }
121
122
123
124 static void cbmsys (const char* sys)
125 /* Define a CBM system */
126 {
127     DefineNumericMacro ("__CBM__", 1);
128     DefineNumericMacro (sys, 1);
129 }
130
131
132
133 static void SetSys (const char* Sys)
134 /* Define a target system */
135 {
136     switch (Target = FindTarget (Sys)) {
137
138         case TGT_NONE:
139             break;
140
141         case TGT_ATARI:
142             DefineNumericMacro ("__ATARI__", 1);
143             break;
144
145         case TGT_C64:
146             cbmsys ("__C64__");
147             break;
148
149         case TGT_C128:
150             cbmsys ("__C128__");
151             break;
152
153         case TGT_ACE:
154             cbmsys ("__ACE__");
155             break;
156
157         case TGT_PLUS4:
158             cbmsys ("__PLUS4__");
159             break;
160
161         case TGT_CBM510:
162             cbmsys ("__CBM510__");
163             break;
164
165         case TGT_CBM610:
166             cbmsys ("__CBM610__");
167             break;
168
169         case TGT_PET:
170             cbmsys ("__PET__");
171             break;
172
173         case TGT_BBC:
174             DefineNumericMacro ("__BBC__", 1);
175             break;
176
177         case TGT_APPLE2:
178             DefineNumericMacro ("__APPLE2__", 1);
179             break;
180
181         case TGT_GEOS:
182             /* Do not handle as a CBM system */
183             DefineNumericMacro ("__GEOS__", 1);
184             break;
185
186         default:
187             AbEnd ("Unknown target system type");
188     }
189
190     /* Initialize the translation tables for the target system */
191     TgtTranslateInit ();
192 }
193
194
195
196 static void DoCreateDep (const char* OutputName)
197 /* Create the dependency file */
198 {
199     /* Make the dependency file name from the output file name */
200     char* DepName = MakeFilename (OutputName, ".u");
201
202     /* Open the file */
203     FILE* F = fopen (DepName, "w");
204     if (F == 0) {
205         Fatal ("Cannot open dependency file `%s': %s", DepName, strerror (errno));
206     }
207
208     /* Write the dependencies to the file */
209     WriteDependencies (F, OutputName);
210
211     /* Close the file, check for errors */
212     if (fclose (F) != 0) {
213         remove (DepName);
214         Fatal ("Cannot write to dependeny file (disk full?)");
215     }
216
217     /* Free the name */
218     xfree (DepName);
219 }
220
221
222
223 static void DefineSym (const char* Def)
224 /* Define a symbol on the command line */
225 {
226     const char* P = Def;
227
228     /* The symbol must start with a character or underline */
229     if (Def [0] != '_' && !IsAlpha (Def [0])) {
230         InvDef (Def);
231     }
232
233     /* Check the symbol name */
234     while (IsAlNum (*P) || *P == '_') {
235         ++P;
236     }
237
238     /* Do we have a value given? */
239     if (*P != '=') {
240         if (*P != '\0') {
241             InvDef (Def);
242         }
243         /* No value given. Define the macro with the value 1 */
244         DefineNumericMacro (Def, 1);
245     } else {
246         /* We have a value, P points to the '=' character. Since the argument
247          * is const, create a copy and replace the '=' in the copy by a zero
248          * terminator.
249          */
250         char* Q;
251         unsigned Len = strlen (Def)+1;
252         char* S = (char*) xmalloc (Len);
253         memcpy (S, Def, Len);
254         Q = S + (P - Def);
255         *Q++ = '\0';
256
257         /* Define this as a macro */
258         DefineTextMacro (S, Q);
259
260         /* Release the allocated memory */
261         xfree (S);
262     }
263 }
264
265
266
267 static void CheckSegName (const char* Seg)
268 /* Abort if the given name is not a valid segment name */
269 {
270     /* Print an error and abort if the name is not ok */
271     if (!ValidSegName (Seg)) {
272         AbEnd ("Segment name `%s' is invalid", Seg);
273     }
274 }
275
276
277
278 static void OptAddSource (const char* Opt, const char* Arg)
279 /* Add source lines as comments in generated assembler file */
280 {
281     AddSource = 1;
282 }
283
284
285
286 static void OptAnsi (const char* Opt, const char* Arg)
287 /* Compile in strict ANSI mode */
288 {
289     ANSI = 1;
290 }
291
292
293
294 static void OptBssName (const char* Opt, const char* Arg)
295 /* Handle the --bss-name option */
296 {                          
297     /* Check for a valid name */
298     CheckSegName (Arg);
299
300     /* Set the name */
301     NewSegName (SEG_BSS, Arg);
302 }
303
304
305
306 static void OptCheckStack (const char* Opt, const char* Arg)
307 /* Handle the --check-stack option */
308 {
309     CheckStack = 1;
310 }
311
312
313
314 static void OptCodeName (const char* Opt, const char* Arg)
315 /* Handle the --code-name option */
316 {
317     /* Check for a valid name */
318     CheckSegName (Arg);
319
320     /* Set the name */
321     NewSegName (SEG_CODE, Arg);
322 }
323
324
325
326 static void OptCodeSize (const char* Opt, const char* Arg)
327 /* Handle the --codesize option */
328 {
329     /* Numeric argument expected */
330     if (sscanf (Arg, "%u", &CodeSizeFactor) != 1 ||
331         CodeSizeFactor < 100 ||
332         CodeSizeFactor > 1000) {
333         AbEnd ("Argument for %s is invalid", Opt);
334     }
335 }
336
337
338
339 static void OptCreateDep (const char* Opt, const char* Arg)
340 /* Handle the --create-dep option */
341 {
342     CreateDep = 1;
343 }
344
345
346
347 static void OptCPU (const char* Opt, const char* Arg)
348 /* Handle the --cpu option */
349 {
350     if (strcmp (Arg, "6502") == 0) {
351         CPU = CPU_6502;
352     } else if (strcmp (Arg, "65C02") == 0) {
353         CPU = CPU_65C02;
354     } else {
355         AbEnd ("Invalid CPU: `%s'", Arg);
356     }
357 }
358
359
360
361 static void OptDataName (const char* Opt, const char* Arg)
362 /* Handle the --code-name option */
363 {
364     /* Check for a valid name */
365     CheckSegName (Arg);
366
367     /* Set the name */
368     NewSegName (SEG_DATA, Arg);
369 }
370
371
372
373 static void OptDebug (const char* Opt, const char* Arg)
374 /* Compiler debug mode */
375 {
376     Debug = 1;
377 }
378
379
380
381 static void OptDebugInfo (const char* Opt, const char* Arg)
382 /* Add debug info to the object file */
383 {
384     DebugInfo = 1;
385 }
386
387
388
389 static void OptDebugOpt (const char* Opt, const char* Arg)
390 /* Debug optimization steps */
391 {
392     char Buf [128];
393     char* Line;
394
395     /* Open the file */
396     FILE* F = fopen (Arg, "r");
397     if (F == 0) {
398         AbEnd ("Cannot open `%s': %s", Arg, strerror (errno));
399     }
400
401     /* Read line by line, ignore empty lines and switch optimization
402      * steps on/off.
403      */
404     while (fgets (Buf, sizeof (Buf), F) != 0) {
405
406         /* Remove trailing control chars. This will also remove the
407          * trailing newline.
408          */
409         unsigned Len = strlen (Buf);
410         while (Len > 0 && IsControl (Buf[Len-1])) {
411             --Len;
412         }
413         Buf[Len] = '\0';
414
415         /* Get a pointer to the buffer and remove leading white space */
416         Line = Buf;
417         while (IsBlank (*Line)) {
418             ++Line;
419         }
420
421         /* Check the first character and enable/disable the step or
422          * ignore the line
423          */
424         switch (*Line) {
425
426             case '\0':
427             case '#':
428             case ';':
429                 /* Empty or comment line */
430                 continue;
431
432             case '-':
433                 DisableOpt (Line+1);
434                 break;
435
436             case '+':
437                 ++Line;
438                 /* FALLTHROUGH */
439
440             default:
441                 EnableOpt (Line);
442                 break;
443
444         }
445
446     }
447
448     /* Close the file, no error check here since we were just reading and
449      * this is only a debug function.
450      */
451     (void) fclose (F);
452 }
453
454
455
456 static void OptDisableOpt (const char* Opt, const char* Arg)
457 /* Disable an optimization step */
458 {
459     DisableOpt (Arg);
460 }
461
462
463
464 static void OptEnableOpt (const char* Opt, const char* Arg)
465 /* Enable an optimization step */
466 {
467     EnableOpt (Arg);
468 }
469
470
471
472 static void OptHelp (const char* Opt, const char* Arg)
473 /* Print usage information and exit */
474 {
475     Usage ();
476     exit (EXIT_SUCCESS);
477 }
478
479
480
481 static void OptIncludeDir (const char* Opt, const char* Arg)
482 /* Add an include search path */
483 {
484     AddIncludePath (Arg, INC_SYS | INC_USER);
485 }
486
487
488
489 static void OptListOptSteps (const char* Opt, const char* Arg)
490 /* List all optimizer steps */
491 {
492     /* List the optimizer steps */
493     ListOptSteps (stdout);
494
495     /* Terminate */
496     exit (EXIT_SUCCESS);
497 }
498
499
500
501 static void OptRodataName (const char* Opt, const char* Arg)
502 /* Handle the --rodata-name option */
503 {
504     /* Check for a valid name */
505     CheckSegName (Arg);
506
507     /* Set the name */
508     NewSegName (SEG_RODATA, Arg);
509 }
510
511
512
513 static void OptSignedChars (const char* Opt, const char* Arg)
514 /* Make default characters signed */
515 {
516     SignedChars = 1;
517 }
518
519
520
521 static void OptStaticLocals (const char* Opt, const char* Arg)
522 /* Place local variables in static storage */
523 {
524     StaticLocals = 1;
525 }
526
527
528
529 static void OptTarget (const char* Opt, const char* Arg)
530 /* Set the target system */
531 {
532     SetSys (Arg);
533 }
534
535
536
537 static void OptVerbose (const char* Opt, const char* Arg)
538 /* Increase verbosity */
539 {
540     ++Verbosity;
541 }
542
543
544
545 static void OptVersion (const char* Opt, const char* Arg)
546 /* Print the assembler version */
547 {
548     fprintf (stderr,
549              "cc65 V%u.%u.%u\n",
550              VER_MAJOR, VER_MINOR, VER_PATCH);
551 }
552
553
554
555 int main (int argc, char* argv[])
556 {
557     /* Program long options */
558     static const LongOpt OptTab[] = {
559         { "--add-source",       0,      OptAddSource            },
560         { "--ansi",             0,      OptAnsi                 },
561         { "--bss-name",         1,      OptBssName              },
562         { "--check-stack",      0,      OptCheckStack           },
563         { "--code-name",        1,      OptCodeName             },
564         { "--codesize",         1,      OptCodeSize             },
565         { "--create-dep",       0,      OptCreateDep            },
566         { "--cpu",              1,      OptCPU                  },
567         { "--data-name",        1,      OptDataName             },
568         { "--debug",            0,      OptDebug                },
569         { "--debug-info",       0,      OptDebugInfo            },
570         { "--debug-opt",        1,      OptDebugOpt             },
571         { "--disable-opt",      1,      OptDisableOpt           },
572         { "--enable-opt",       1,      OptEnableOpt,           },
573         { "--help",             0,      OptHelp                 },
574         { "--include-dir",      1,      OptIncludeDir           },
575         { "--list-opt-steps",   0,      OptListOptSteps         },
576         { "--rodata-name",      1,      OptRodataName           },
577         { "--signed-chars",     0,      OptSignedChars          },
578         { "--static-locals",    0,      OptStaticLocals         },
579         { "--target",           1,      OptTarget               },
580         { "--verbose",          0,      OptVerbose              },
581         { "--version",          0,      OptVersion              },
582     };
583
584     int I;
585
586     /* Initialize the output file name */
587     const char* OutputFile = 0;
588     const char* InputFile  = 0;
589
590     /* Initialize the cmdline module */
591     InitCmdLine (&argc, &argv, "cc65");
592
593     /* Initialize the default segment names */
594     InitSegNames ();
595
596     /* Parse the command line */
597     I = 1;
598     while (I < (int)ArgCount) {
599
600         const char* P;
601
602         /* Get the argument */
603         const char* Arg = ArgVec[I];
604
605         /* Check for an option */
606         if (Arg [0] == '-') {
607
608             switch (Arg [1]) {
609
610                 case '-':
611                     LongOption (&I, OptTab, sizeof(OptTab)/sizeof(OptTab[0]));
612                     break;
613
614                 case 'd':
615                     OptDebug (Arg, 0);
616                     break;
617
618                 case 'h':
619                 case '?':
620                     OptHelp (Arg, 0);
621                     break;
622
623                 case 'g':
624                     OptDebugInfo (Arg, 0);
625                     break;
626
627                 case 'j':
628                     OptSignedChars (Arg, 0);
629                     break;
630
631                 case 'o':
632                     OutputFile = GetArg (&I, 2);
633                     break;
634
635                 case 't':
636                     OptTarget (Arg, GetArg (&I, 2));
637                     break;
638
639                 case 'u':
640                     OptCreateDep (Arg, 0);
641                     break;
642
643                 case 'v':
644                     OptVerbose (Arg, 0);
645                     break;
646
647                 case 'A':
648                     OptAnsi (Arg, 0);
649                     break;
650
651                 case 'C':
652                     P = Arg + 2;
653                     while (*P) {
654                         switch (*P++) {
655                             case 'l':
656                                 OptStaticLocals (Arg, 0);
657                                 break;
658                             default:
659                                 UnknownOption (Arg);
660                                 break;
661                         }
662                     }
663                     break;
664
665                 case 'D':
666                     DefineSym (GetArg (&I, 2));
667                     break;
668
669                 case 'I':
670                     OptIncludeDir (Arg, GetArg (&I, 2));
671                     break;
672
673                 case 'O':
674                     Optimize = 1;
675                     P = Arg + 2;
676                     while (*P) {
677                         switch (*P++) {
678                             case 'f':
679                                 sscanf (P, "%lx", (long*) &OptDisable);
680                                 break;
681                             case 'i':
682                                 FavourSize = 0;
683                                 CodeSizeFactor = 200;
684                                 break;
685                             case 'r':
686                                 EnableRegVars = 1;
687                                 break;
688                             case 's':
689                                 InlineStdFuncs = 1;
690                                 break;
691                         }
692                     }
693                     break;
694
695                 case 'T':
696                     OptAddSource (Arg, 0);
697                     break;
698
699                 case 'V':
700                     OptVersion (Arg, 0);
701                     break;
702
703                 case 'W':
704                     NoWarn = 1;
705                     break;
706
707                 default:
708                     UnknownOption (Arg);
709                     break;
710             }
711         } else {
712             if (InputFile) {
713                 fprintf (stderr, "additional file specs ignored\n");
714             } else {
715                 InputFile = Arg;
716             }
717         }
718
719         /* Next argument */
720         ++I;
721     }
722
723     /* Did we have a file spec on the command line? */
724     if (InputFile == 0) {
725         AbEnd ("No input files");
726     }
727
728     /* Create the output file name if it was not explicitly given */
729     if (OutputFile == 0) {
730         OutputFile = MakeFilename (InputFile, ".s");
731     }
732
733     /* Go! */
734     Compile (InputFile);
735
736     /* Create the output file if we didn't had any errors */
737     if (ErrorCount == 0 || Debug) {
738
739         FILE* F;
740
741 #if 0
742         /* Optimize the output if requested */
743         if (Optimize) {
744             OptDoOpt ();
745         }
746 #endif
747
748         /* Open the file */
749         F = fopen (OutputFile, "w");
750         if (F == 0) {
751             Fatal ("Cannot open output file `%s': %s", OutputFile, strerror (errno));
752         }
753
754         /* Write the output to the file */
755         WriteOutput (F);
756
757         /* Close the file, check for errors */
758         if (fclose (F) != 0) {
759             remove (OutputFile);
760             Fatal ("Cannot write to output file (disk full?)");
761         }
762
763         /* Create dependencies if requested */
764         if (CreateDep) {
765             DoCreateDep (OutputFile);
766         }
767
768     }
769
770     /* Return an apropriate exit code */
771     return (ErrorCount > 0)? EXIT_FAILURE : EXIT_SUCCESS;
772 }
773
774
775