]> git.sur5r.net Git - cc65/blob - src/cc65/compile.c
d79ef350b9ff102d86afc8b45f787bf0d5c5065b
[cc65] / src / cc65 / compile.c
1 /*****************************************************************************/
2 /*                                                                           */
3 /*                                 compile.c                                 */
4 /*                                                                           */
5 /*                       Top level compiler subroutine                       */
6 /*                                                                           */
7 /*                                                                           */
8 /*                                                                           */
9 /* (C) 2000-2013, 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         /* Disallow ASM statements on global level */
95         if (CurTok.Tok == TOK_ASM) {
96             Error ("__asm__ is not allowed here");
97             /* Parse and remove the statement for error recovery */
98             AsmStatement ();
99             ConsumeSemi ();
100             RemoveGlobalCode ();
101             continue;
102         }
103
104         /* Check for a #pragma */
105         if (CurTok.Tok == TOK_PRAGMA) {
106             DoPragma ();
107             continue;
108         }
109
110         /* Read variable defs and functions */
111         ParseDeclSpec (&Spec, SC_EXTERN | SC_STATIC, T_INT);
112
113         /* Don't accept illegal storage classes */
114         if ((Spec.StorageClass & SC_TYPE) == 0) {
115             if ((Spec.StorageClass & SC_AUTO) != 0 ||
116                 (Spec.StorageClass & SC_REGISTER) != 0) {
117                 Error ("Illegal storage class");
118                 Spec.StorageClass = SC_EXTERN | SC_STATIC;
119             }
120         }
121
122         /* Check if this is only a type declaration */
123         if (CurTok.Tok == TOK_SEMI) {
124             CheckEmptyDecl (&Spec);
125             NextToken ();
126             continue;
127         }
128
129         /* Read declarations for this type */
130         Entry = 0;
131         comma = 0;
132         while (1) {
133
134             Declaration         Decl;
135
136             /* Read the next declaration */
137             ParseDecl (&Spec, &Decl, DM_NEED_IDENT);
138             if (Decl.Ident[0] == '\0') {
139                 NextToken ();
140                 break;
141             }
142
143             /* Check if we must reserve storage for the variable. We do this,
144             **
145             **   - if it is not a typedef or function,
146             **   - if we don't had a storage class given ("int i")
147             **   - if the storage class is explicitly specified as static,
148             **   - or if there is an initialization.
149             **
150             ** This means that "extern int i;" will not get storage allocated.
151             */
152             if ((Decl.StorageClass & SC_FUNC) != SC_FUNC          &&
153                 (Decl.StorageClass & SC_TYPEMASK) != SC_TYPEDEF    &&
154                 ((Spec.Flags & DS_DEF_STORAGE) != 0         ||
155                  (Decl.StorageClass & (SC_EXTERN|SC_STATIC)) == SC_STATIC ||
156                  ((Decl.StorageClass & SC_EXTERN) != 0 &&
157                   CurTok.Tok == TOK_ASSIGN))) {
158
159                 /* We will allocate storage */
160                 Decl.StorageClass |= SC_STORAGE;
161             }
162
163             /* If this is a function declarator that is not followed by a comma
164             ** or semicolon, it must be followed by a function body. If this is
165             ** the case, convert an empty parameter list into one accepting no
166             ** parameters (same as void) as required by the standard.
167             */
168             if ((Decl.StorageClass & SC_FUNC) != 0 &&
169                 (CurTok.Tok != TOK_COMMA)          &&
170                 (CurTok.Tok != TOK_SEMI)) {
171
172                 FuncDesc* D = GetFuncDesc (Decl.Type);
173                 if (D->Flags & FD_EMPTY) {
174                     D->Flags = (D->Flags & ~(FD_EMPTY | FD_VARIADIC)) | FD_VOID_PARAM;
175                 }
176             }
177
178             /* Add an entry to the symbol table */
179             Entry = AddGlobalSym (Decl.Ident, Decl.Type, Decl.StorageClass);
180
181             /* Add declaration attributes */
182             SymUseAttr (Entry, &Decl);
183
184             /* Reserve storage for the variable if we need to */
185             if (Decl.StorageClass & SC_STORAGE) {
186
187                 /* Get the size of the variable */
188                 unsigned Size = SizeOf (Decl.Type);
189
190                 /* Allow initialization */
191                 if (CurTok.Tok == TOK_ASSIGN) {
192
193                     /* This is a definition */
194                     if (SymIsDef (Entry)) {
195                         Error ("Global variable `%s' has already been defined",
196                                Entry->Name);
197                     }
198                     Entry->Flags |= SC_DEF;
199
200                     /* We cannot initialize types of unknown size, or
201                     ** void types in ISO modes.
202                     */
203                     if (Size == 0) {
204                         if (!IsTypeVoid (Decl.Type)) {
205                             if (!IsTypeArray (Decl.Type)) {
206                                 /* Size is unknown and not an array */
207                                 Error ("Variable `%s' has unknown size", Decl.Ident);
208                             }
209                         } else if (IS_Get (&Standard) != STD_CC65) {
210                             /* We cannot declare variables of type void */
211                             Error ("Illegal type for variable `%s'", Decl.Ident);
212                         }
213                     }
214
215                     /* Switch to the data or rodata segment. For arrays, check
216                      ** the element qualifiers, since not the array but its
217                      ** elements are const.
218                      */
219                     if (IsQualConst (GetBaseElementType (Decl.Type))) {
220                         g_userodata ();
221                     } else {
222                         g_usedata ();
223                     }
224
225                     /* Define a label */
226                     g_defgloblabel (Entry->Name);
227
228                     /* Skip the '=' */
229                     NextToken ();
230
231                     /* Parse the initialization */
232                     ParseInit (Entry->Type);
233                 } else {
234
235                     if (IsTypeVoid (Decl.Type)) {
236                         /* We cannot declare variables of type void */
237                         Error ("Illegal type for variable `%s'", Decl.Ident);
238                         Entry->Flags &= ~(SC_STORAGE | SC_DEF);
239                     } else if (Size == 0) {
240                         /* Size is unknown. Is it an array? */
241                         if (!IsTypeArray (Decl.Type)) {
242                             Error ("Variable `%s' has unknown size", Decl.Ident);
243                         }
244                         Entry->Flags &= ~(SC_STORAGE | SC_DEF);
245                     } else {
246                         /* A global (including static) uninitialized variable is
247                         ** only a tentative definition. For example, this is valid:
248                         ** int i;
249                         ** int i;
250                         ** static int j;
251                         ** static int j = 42;
252                         ** Code for them will be generated by FinishCompile().
253                         ** For now, just save the BSS segment name
254                         ** (can be set by #pragma bss-name).
255                         */
256                         const char* bssName = GetSegName (SEG_BSS);
257
258                         if (Entry->V.BssName && strcmp (Entry->V.BssName, bssName) != 0) {
259                             Error ("Global variable `%s' already was defined in the `%s' segment.",
260                                    Entry->Name, Entry->V.BssName);
261                         }
262                         Entry->V.BssName = xstrdup (bssName);
263                     }
264                 }
265
266             }
267
268             /* Check for end of declaration list */
269             if (CurTok.Tok == TOK_COMMA) {
270                 NextToken ();
271                 comma = 1;
272             } else {
273                 break;
274             }
275         }
276
277         /* Function declaration? */
278         if (Entry && IsTypeFunc (Entry->Type)) {
279
280             /* Function */
281             if (!comma) {
282                 if (CurTok.Tok == TOK_SEMI) {
283                     /* Prototype only */
284                     NextToken ();
285                 } else {
286
287                     /* Function body. Check for duplicate function definitions */
288                     if (SymIsDef (Entry)) {
289                         Error ("Body for function `%s' has already been defined",
290                                Entry->Name);
291                     }
292
293                     /* Parse the function body */
294                     NewFunc (Entry);
295                 }
296             }
297
298         } else {
299
300             /* Must be followed by a semicolon */
301             ConsumeSemi ();
302
303         }
304     }
305 }
306
307
308
309 void Compile (const char* FileName)
310 /* Top level compile routine. Will setup things and call the parser. */
311 {
312     char        DateStr[32];
313     char        TimeStr[32];
314     time_t      Time;
315     struct tm*  TM;
316
317     /* Since strftime is locale dependent, we need the abbreviated month names
318     ** in English.
319     */
320     static const char MonthNames[12][4] = {
321         "Jan", "Feb", "Mar", "Apr", "May", "Jun",
322         "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
323     };
324
325     /* Add macros that are always defined */
326     DefineNumericMacro ("__CC65__", GetVersionAsNumber ());
327
328     /* Language standard that is supported */
329     DefineNumericMacro ("__CC65_STD_C89__", STD_C89);
330     DefineNumericMacro ("__CC65_STD_C99__", STD_C99);
331     DefineNumericMacro ("__CC65_STD_CC65__", STD_CC65);
332     DefineNumericMacro ("__CC65_STD__", IS_Get (&Standard));
333
334     /* Optimization macros. Since no source code has been parsed for now, the
335     ** IS_Get functions access the values in effect now, regardless of any
336     ** changes using #pragma later.
337     */
338     if (IS_Get (&Optimize)) {
339         DefineNumericMacro ("__OPT__", 1);
340     }
341     {
342         long CodeSize = IS_Get (&CodeSizeFactor);
343         if (CodeSize > 100) {
344             DefineNumericMacro ("__OPT_i__", CodeSize);
345         }
346     }
347     if (IS_Get (&EnableRegVars)) {
348         DefineNumericMacro ("__OPT_r__", 1);
349     }
350     if (IS_Get (&InlineStdFuncs)) {
351         DefineNumericMacro ("__OPT_s__", 1);
352     }
353     if (IS_Get (&EagerlyInlineFuncs)) {
354         DefineNumericMacro ("__EAGERLY_INLINE_FUNCS__", 1);
355     }
356
357     /* __TIME__ and __DATE__ macros */
358     Time = time (0);
359     TM   = localtime (&Time);
360     xsprintf (DateStr, sizeof (DateStr), "\"%s %2d %d\"",
361               MonthNames[TM->tm_mon], TM->tm_mday, TM->tm_year + 1900);
362     strftime (TimeStr, sizeof (TimeStr), "\"%H:%M:%S\"", TM);
363     DefineTextMacro ("__DATE__", DateStr);
364     DefineTextMacro ("__TIME__", TimeStr);
365
366     /* Other standard macros */
367     /* DefineNumericMacro ("__STDC__", 1);      <- not now */
368     DefineNumericMacro ("__STDC_HOSTED__", 1);
369
370     /* Create the base lexical level */
371     EnterGlobalLevel ();
372
373     /* Create the global code and data segments */
374     CreateGlobalSegments ();
375
376     /* Initialize the literal pool */
377     InitLiteralPool ();
378
379     /* Generate the code generator preamble */
380     g_preamble ();
381
382     /* Open the input file */
383     OpenMainFile (FileName);
384
385     /* Are we supposed to compile or just preprocess the input? */
386     if (PreprocessOnly) {
387
388         /* Open the file */
389         OpenOutputFile ();
390
391         /* Preprocess each line and write it to the output file */
392         while (NextLine ()) {
393             Preprocess ();
394             WriteOutput ("%.*s\n", (int) SB_GetLen (Line), SB_GetConstBuf (Line));
395         }
396
397         /* Close the output file */
398         CloseOutputFile ();
399
400     } else {
401
402         /* Ok, start the ball rolling... */
403         Parse ();
404
405     }
406
407     if (Debug) {
408         PrintMacroStats (stdout);
409     }
410
411     /* Print an error report */
412     ErrorReport ();
413 }
414
415
416
417 void FinishCompile (void)
418 /* Emit literals, externals, debug info, do cleanup and optimizations */
419 {
420     SymEntry* Entry;
421
422     /* Walk over all global symbols:
423     ** - for functions, do clean-up and optimizations
424     ** - generate code for uninitialized global variables
425     */
426     for (Entry = GetGlobalSymTab ()->SymHead; Entry; Entry = Entry->NextSym) {
427         if (SymIsOutputFunc (Entry)) {
428             /* Function which is defined and referenced or extern */
429             MoveLiteralPool (Entry->V.F.LitPool);
430             CS_MergeLabels (Entry->V.F.Seg->Code);
431             RunOpt (Entry->V.F.Seg->Code);
432         } else if ((Entry->Flags & (SC_STORAGE | SC_DEF | SC_STATIC)) == (SC_STORAGE | SC_STATIC)) {
433             /* Assembly definition of uninitialized global variable */
434
435             /* Set the segment name only when it changes */
436             if (strcmp (GetSegName (SEG_BSS), Entry->V.BssName) != 0) {
437                 SetSegName (SEG_BSS, Entry->V.BssName);
438                 g_segname (SEG_BSS);
439             }
440             g_usebss ();
441             g_defgloblabel (Entry->Name);
442             g_res (SizeOf (Entry->Type));
443             /* Mark as defined; so that it will be exported, not imported */
444             Entry->Flags |= SC_DEF;
445         }
446     }
447
448     /* Output the literal pool */
449     OutputLiteralPool ();
450
451     /* Emit debug infos if enabled */
452     EmitDebugInfo ();
453
454     /* Write imported/exported symbols */
455     EmitExternals ();
456
457     /* Leave the main lexical level */
458     LeaveGlobalLevel ();
459 }