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