]> git.sur5r.net Git - cc65/blob - src/cc65/compile.c
New option and #pragma --local-strings that causes string literals to be
[cc65] / src / cc65 / compile.c
1 /*****************************************************************************/
2 /*                                                                           */
3 /*                                 compile.c                                 */
4 /*                                                                           */
5 /*                       Top level compiler subroutine                       */
6 /*                                                                           */
7 /*                                                                           */
8 /*                                                                           */
9 /* (C) 2000-2009, Ullrich von Bassewitz                                      */
10 /*                Roemerstrasse 52                                           */
11 /*                D-70794 Filderstadt                                        */
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 <stdlib.h>
37 #include <time.h>
38
39 /* common */
40 #include "debugflag.h"
41 #include "version.h"
42 #include "xmalloc.h"
43 #include "xsprintf.h"
44
45 /* cc65 */
46 #include "asmlabel.h"
47 #include "asmstmt.h"
48 #include "codegen.h"
49 #include "codeopt.h"
50 #include "compile.h"
51 #include "declare.h"
52 #include "error.h"
53 #include "expr.h"
54 #include "function.h"
55 #include "global.h"
56 #include "input.h"
57 #include "litpool.h"
58 #include "macrotab.h"
59 #include "output.h"
60 #include "pragma.h"
61 #include "preproc.h"
62 #include "standard.h"
63 #include "symtab.h"
64
65
66
67 /*****************************************************************************/
68 /*                                   Code                                    */
69 /*****************************************************************************/
70
71
72
73 static void Parse (void)
74 /* Top level parser routine. */
75 {
76     int comma;
77     SymEntry* Entry;
78
79     /* Go... */
80     NextToken ();
81     NextToken ();
82
83     /* Parse until end of input */
84     while (CurTok.Tok != TOK_CEOF) {
85
86         DeclSpec        Spec;
87
88         /* Check for empty statements */
89         if (CurTok.Tok == TOK_SEMI) {
90             NextToken ();
91             continue;
92         }
93
94         /* Check for an ASM statement (which is allowed also on global level) */
95         if (CurTok.Tok == TOK_ASM) {
96             AsmStatement ();
97             ConsumeSemi ();
98             continue;
99         }
100
101         /* Check for a #pragma */
102         if (CurTok.Tok == TOK_PRAGMA) {
103             DoPragma ();
104             continue;
105         }
106
107         /* Read variable defs and functions */
108         ParseDeclSpec (&Spec, SC_EXTERN | SC_STATIC, T_INT);
109
110         /* Don't accept illegal storage classes */
111         if ((Spec.StorageClass & SC_TYPE) == 0) {
112             if ((Spec.StorageClass & SC_AUTO) != 0 ||
113                 (Spec.StorageClass & SC_REGISTER) != 0) {
114                 Error ("Illegal storage class");
115                 Spec.StorageClass = SC_EXTERN | SC_STATIC;
116             }
117         }
118
119         /* Check if this is only a type declaration */
120         if (CurTok.Tok == TOK_SEMI) {
121             CheckEmptyDecl (&Spec);
122             NextToken ();
123             continue;
124         }
125
126         /* Read declarations for this type */
127         Entry = 0;
128         comma = 0;
129         while (1) {
130
131             Declaration         Decl;
132
133             /* Read the next declaration */
134             ParseDecl (&Spec, &Decl, DM_NEED_IDENT);
135             if (Decl.Ident[0] == '\0') {
136                 NextToken ();
137                 break;
138             }
139
140             /* Check if we must reserve storage for the variable. We do this,
141              * if it is not a typedef or function, if we don't had a storage
142              * class given ("int i") or if the storage class is explicitly
143              * specified as static. This means that "extern int i" will not
144              * get storage allocated.
145              */
146             if ((Decl.StorageClass & SC_FUNC) != SC_FUNC          &&
147                 (Decl.StorageClass & SC_TYPEDEF) != SC_TYPEDEF    &&
148                 ((Spec.Flags & DS_DEF_STORAGE) != 0  ||
149                  (Decl.StorageClass & (SC_STATIC | SC_EXTERN)) == SC_STATIC)) {
150
151                 /* We will allocate storage */
152                 Decl.StorageClass |= SC_STORAGE | SC_DEF;
153             }
154
155             /* If this is a function declarator that is not followed by a comma
156              * or semicolon, it must be followed by a function body. If this is
157              * the case, convert an empty parameter list into one accepting no
158              * parameters (same as void) as required by the standard.
159              */
160             if ((Decl.StorageClass & SC_FUNC) != 0 &&
161                 (CurTok.Tok != TOK_COMMA)          &&
162                 (CurTok.Tok != TOK_SEMI)) {
163
164                 FuncDesc* D = GetFuncDesc (Decl.Type);
165                 if (D->Flags & FD_EMPTY) {
166                     D->Flags = (D->Flags & ~(FD_EMPTY | FD_VARIADIC)) | FD_VOID_PARAM;
167                 }
168             }
169
170             /* Add an entry to the symbol table */
171             Entry = AddGlobalSym (Decl.Ident, Decl.Type, Decl.StorageClass);
172
173             /* Add declaration attributes */
174             SymUseAttr (Entry, &Decl);
175
176             /* Reserve storage for the variable if we need to */
177             if (Decl.StorageClass & SC_STORAGE) {
178
179                 /* Get the size of the variable */
180                 unsigned Size = SizeOf (Decl.Type);
181
182                 /* Allow initialization */
183                 if (CurTok.Tok == TOK_ASSIGN) {
184
185                     /* We cannot initialize types of unknown size, or
186                      * void types in non ANSI mode.
187                      */
188                     if (Size == 0) {
189                         if (!IsTypeVoid (Decl.Type)) {
190                             if (!IsTypeArray (Decl.Type)) {
191                                 /* Size is unknown and not an array */
192                                 Error ("Variable `%s' has unknown size", Decl.Ident);
193                             }
194                         } else if (IS_Get (&Standard) != STD_CC65) {
195                             /* We cannot declare variables of type void */
196                             Error ("Illegal type for variable `%s'", Decl.Ident);
197                         }
198                     }
199
200                     /* Switch to the data or rodata segment. For arrays, check
201                       * the element qualifiers, since not the array but its
202                       * elements are const.
203                       */
204                     if (IsQualConst (Decl.Type) ||
205                         (IsTypeArray (Decl.Type) &&
206                          IsQualConst (GetElementType (Decl.Type)))) {
207                         g_userodata ();
208                     } else {
209                         g_usedata ();
210                     }
211
212                     /* Define a label */
213                     g_defgloblabel (Entry->Name);
214
215                     /* Skip the '=' */
216                     NextToken ();
217
218                     /* Parse the initialization */
219                     ParseInit (Entry->Type);
220                 } else {
221
222                     if (IsTypeVoid (Decl.Type)) {
223                         /* We cannot declare variables of type void */
224                         Error ("Illegal type for variable `%s'", Decl.Ident);
225                         Entry->Flags &= ~(SC_STORAGE | SC_DEF);
226                     } else if (Size == 0) {
227                         /* Size is unknown. Is it an array? */
228                         if (!IsTypeArray (Decl.Type)) {
229                             Error ("Variable `%s' has unknown size", Decl.Ident);
230                         }
231                         Entry->Flags &= ~(SC_STORAGE | SC_DEF);
232                     }
233
234                     /* Allocate storage if it is still needed */
235                     if (Entry->Flags & SC_STORAGE) {
236
237                         /* Switch to the BSS segment */
238                         g_usebss ();
239
240                         /* Define a label */
241                         g_defgloblabel (Entry->Name);
242
243                         /* Allocate space for uninitialized variable */
244                         g_res (Size);
245                     }
246                 }
247
248             }
249
250             /* Check for end of declaration list */
251             if (CurTok.Tok == TOK_COMMA) {
252                 NextToken ();
253                 comma = 1;
254             } else {
255                 break;
256             }
257         }
258
259         /* Function declaration? */
260         if (Entry && IsTypeFunc (Entry->Type)) {
261
262             /* Function */
263             if (!comma) {
264                 if (CurTok.Tok == TOK_SEMI) {
265                     /* Prototype only */
266                     NextToken ();
267                 } else {
268
269                     /* Function body. Check for duplicate function definitions */
270                     if (SymIsDef (Entry)) {
271                         Error ("Body for function `%s' has already been defined",
272                                Entry->Name);
273                     }
274
275                     /* Parse the function body */
276                     NewFunc (Entry);
277                 }
278             }
279
280         } else {
281
282             /* Must be followed by a semicolon */
283             ConsumeSemi ();
284
285         }
286     }
287 }
288
289
290
291 void Compile (const char* FileName)
292 /* Top level compile routine. Will setup things and call the parser. */
293 {
294     char        DateStr[32];
295     char        TimeStr[32];
296     time_t      Time;
297     struct tm*  TM;
298
299     /* Since strftime is locale dependent, we need the abbreviated month names
300      * in english.
301      */
302     static const char MonthNames[12][4] = {
303         "Jan", "Feb", "Mar", "Apr", "May", "Jun",
304         "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
305     };
306
307     /* Add macros that are always defined */
308     DefineNumericMacro ("__CC65__", GetVersionAsNumber ());
309
310     /* Language standard that is supported */
311     DefineNumericMacro ("__CC65_STD_C89__", STD_C89);
312     DefineNumericMacro ("__CC65_STD_C99__", STD_C99);
313     DefineNumericMacro ("__CC65_STD_CC65__", STD_CC65);
314     DefineNumericMacro ("__CC65_STD__", IS_Get (&Standard));
315
316     /* Optimization macros. Since no source code has been parsed for now, the
317      * IS_Get functions access the values in effect now, regardless of any
318      * changes using #pragma later.
319      */
320     if (IS_Get (&Optimize)) {
321         long CodeSize = IS_Get (&CodeSizeFactor);
322         DefineNumericMacro ("__OPT__", 1);
323         if (CodeSize > 100) {
324             DefineNumericMacro ("__OPT_i__", CodeSize);
325         }
326         if (IS_Get (&EnableRegVars)) {
327             DefineNumericMacro ("__OPT_r__", 1);
328         }
329         if (IS_Get (&InlineStdFuncs)) {
330             DefineNumericMacro ("__OPT_s__", 1);
331         }
332     }
333
334     /* __TIME__ and __DATE__ macros */
335     Time = time (0);
336     TM   = localtime (&Time);
337     xsprintf (DateStr, sizeof (DateStr), "\"%s %2d %d\"",
338               MonthNames[TM->tm_mon], TM->tm_mday, TM->tm_year + 1900);
339     strftime (TimeStr, sizeof (TimeStr), "\"%H:%M:%S\"", TM);
340     DefineTextMacro ("__DATE__", DateStr);
341     DefineTextMacro ("__TIME__", TimeStr);
342
343     /* Other standard macros */
344     /* DefineNumericMacro ("__STDC__", 1);      <- not now */
345     DefineNumericMacro ("__STDC_HOSTED__", 1);
346
347     /* Create the base lexical level */
348     EnterGlobalLevel ();
349
350     /* Create the global code and data segments */
351     CreateGlobalSegments ();
352
353     /* Initialize the literal pool */
354     InitLiteralPool ();
355
356     /* Generate the code generator preamble */
357     g_preamble ();
358
359     /* Open the input file */
360     OpenMainFile (FileName);
361
362     /* Are we supposed to compile or just preprocess the input? */
363     if (PreprocessOnly) {
364
365         /* Open the file */
366         OpenOutputFile ();
367
368         /* Preprocess each line and write it to the output file */
369         while (NextLine ()) {
370             Preprocess ();
371             WriteOutput ("%.*s\n", (int) SB_GetLen (Line), SB_GetConstBuf (Line));
372         }
373
374         /* Close the output file */
375         CloseOutputFile ();
376
377     } else {
378
379         /* Ok, start the ball rolling... */
380         Parse ();
381
382     }
383
384     if (Debug) {
385         PrintMacroStats (stdout);
386     }
387
388     /* Print an error report */
389     ErrorReport ();
390 }
391
392
393
394 void FinishCompile (void)
395 /* Emit literals, externals, do cleanup and optimizations */
396 {
397     SymTable* SymTab;
398     SymEntry* Func;
399
400     /* Walk over all functions, doing cleanup, optimizations ... */
401     SymTab = GetGlobalSymTab ();
402     Func   = SymTab->SymHead;
403     while (Func) {
404         if (SymIsOutputFunc (Func)) {
405             /* Function which is defined and referenced or extern */
406             MoveLiteralPool (Func->V.F.LitPool);
407             CS_MergeLabels (Func->V.F.Seg->Code);
408             RunOpt (Func->V.F.Seg->Code);
409         }
410         Func = Func->NextSym;
411     }
412
413     /* Output the literal pool */
414     OutputLiteralPool ();
415
416     /* Write imported/exported symbols */
417     EmitExternals ();
418
419     /* Leave the main lexical level */
420     LeaveGlobalLevel ();
421 }
422
423
424