]> git.sur5r.net Git - cc65/blob - src/cc65/expr.c
0057e272c4c750212082c1013ba23a4e8697a0f9
[cc65] / src / cc65 / expr.c
1 /* expr.c
2  *
3  * Ullrich von Bassewitz, 21.06.1998
4  */
5
6
7
8 #include <stdio.h>
9 #include <stdlib.h>
10
11 /* common */
12 #include "check.h"
13 #include "debugflag.h"
14 #include "xmalloc.h"
15
16 /* cc65 */
17 #include "asmcode.h"
18 #include "asmlabel.h"
19 #include "asmstmt.h"
20 #include "assignment.h"
21 #include "codegen.h"
22 #include "declare.h"
23 #include "error.h"
24 #include "funcdesc.h"
25 #include "function.h"
26 #include "global.h"
27 #include "litpool.h"
28 #include "macrotab.h"
29 #include "preproc.h"
30 #include "scanner.h"
31 #include "stackptr.h"
32 #include "stdfunc.h"
33 #include "symtab.h"
34 #include "typecmp.h"
35 #include "typeconv.h"
36 #include "expr.h"
37
38
39
40 /*****************************************************************************/
41 /*                                   Data                                    */
42 /*****************************************************************************/
43
44
45
46 /* Generator attributes */
47 #define GEN_NOPUSH      0x01            /* Don't push lhs */
48
49 /* Map a generator function and its attributes to a token */
50 typedef struct {
51     token_t       Tok;                  /* Token to map to */
52     unsigned      Flags;                /* Flags for generator function */
53     void          (*Func) (unsigned, unsigned long);    /* Generator func */
54 } GenDesc;
55
56 /* Descriptors for the operations */
57 static GenDesc GenPASGN  = { TOK_PLUS_ASSIGN,   GEN_NOPUSH,     g_add };
58 static GenDesc GenSASGN  = { TOK_MINUS_ASSIGN,  GEN_NOPUSH,     g_sub };
59 static GenDesc GenMASGN  = { TOK_MUL_ASSIGN,    GEN_NOPUSH,     g_mul };
60 static GenDesc GenDASGN  = { TOK_DIV_ASSIGN,    GEN_NOPUSH,     g_div };
61 static GenDesc GenMOASGN = { TOK_MOD_ASSIGN,    GEN_NOPUSH,     g_mod };
62 static GenDesc GenSLASGN = { TOK_SHL_ASSIGN,    GEN_NOPUSH,     g_asl };
63 static GenDesc GenSRASGN = { TOK_SHR_ASSIGN,    GEN_NOPUSH,     g_asr };
64 static GenDesc GenAASGN  = { TOK_AND_ASSIGN,    GEN_NOPUSH,     g_and };
65 static GenDesc GenXOASGN = { TOK_XOR_ASSIGN,    GEN_NOPUSH,     g_xor };
66 static GenDesc GenOASGN  = { TOK_OR_ASSIGN,     GEN_NOPUSH,     g_or  };
67
68
69
70 /*****************************************************************************/
71 /*                             Function forwards                             */
72 /*****************************************************************************/
73
74
75
76 void hie0 (ExprDesc *lval);
77 /* Parse comma operator. */
78
79
80
81 /*****************************************************************************/
82 /*                             Helper functions                              */
83 /*****************************************************************************/
84
85
86
87 static unsigned GlobalModeFlags (unsigned Flags)
88 /* Return the addressing mode flags for the variable with the given flags */
89 {
90     switch (Flags & E_MASK_LOC) {
91         case E_LOC_GLOBAL:      return CF_EXTERNAL;
92         case E_LOC_STATIC:      return CF_STATIC;
93         case E_LOC_REGISTER:    return CF_REGVAR;
94         default:
95             Internal ("GlobalModeFlags: Invalid flags value: %u", Flags);
96     }
97 }
98
99
100
101 void ExprWithCheck (void (*Func) (ExprDesc*), ExprDesc *Expr)
102 /* Call an expression function with checks. */
103 {
104     /* Remember the stack pointer */
105     int OldSP = StackPtr;
106
107     /* Call the expression function */
108     (*Func) (Expr);
109
110     /* Do some checks if code generation is still constistent */
111     if (StackPtr != OldSP) {
112         if (Debug) {
113             fprintf (stderr,
114                      "Code generation messed up!\n"
115                      "StackPtr is %d, should be %d",
116                      StackPtr, OldSP);
117         } else {
118             Internal ("StackPtr is %d, should be %d\n", StackPtr, OldSP);
119         }
120     }
121 }
122
123
124
125 static type* promoteint (type* lhst, type* rhst)
126 /* In an expression with two ints, return the type of the result */
127 {
128     /* Rules for integer types:
129      *   - If one of the values is a long, the result is long.
130      *   - If one of the values is unsigned, the result is also unsigned.
131      *   - Otherwise the result is an int.
132      */
133     if (IsTypeLong (lhst) || IsTypeLong (rhst)) {
134         if (IsSignUnsigned (lhst) || IsSignUnsigned (rhst)) {
135             return type_ulong;
136         } else {
137             return type_long;
138         }
139     } else {
140         if (IsSignUnsigned (lhst) || IsSignUnsigned (rhst)) {
141             return type_uint;
142         } else {
143             return type_int;
144         }
145     }
146 }
147
148
149
150 static unsigned typeadjust (ExprDesc* lhs, ExprDesc* rhs, int NoPush)
151 /* Adjust the two values for a binary operation. lhs is expected on stack or
152  * to be constant, rhs is expected to be in the primary register or constant.
153  * The function will put the type of the result into lhs and return the
154  * code generator flags for the operation.
155  * If NoPush is given, it is assumed that the operation does not expect the lhs
156  * to be on stack, and that lhs is in a register instead.
157  * Beware: The function does only accept int types.
158  */
159 {
160     unsigned ltype, rtype;
161     unsigned flags;
162
163     /* Get the type strings */
164     type* lhst = lhs->Type;
165     type* rhst = rhs->Type;
166
167     /* Generate type adjustment code if needed */
168     ltype = TypeOf (lhst);
169     if (ED_IsLocAbs (lhs)) {
170         ltype |= CF_CONST;
171     }
172     if (NoPush) {
173         /* Value is in primary register*/
174         ltype |= CF_REG;
175     }
176     rtype = TypeOf (rhst);
177     if (ED_IsLocAbs (rhs)) {
178         rtype |= CF_CONST;
179     }
180     flags = g_typeadjust (ltype, rtype);
181
182     /* Set the type of the result */
183     lhs->Type = promoteint (lhst, rhst);
184
185     /* Return the code generator flags */
186     return flags;
187 }
188
189
190
191 void DefineData (ExprDesc* Expr)
192 /* Output a data definition for the given expression */
193 {
194     switch (ED_GetLoc (Expr)) {
195
196         case E_LOC_ABS:
197             /* Absolute: numeric address or const */
198             g_defdata (TypeOf (Expr->Type) | CF_CONST, Expr->Val, 0);
199             break;
200
201         case E_LOC_GLOBAL:
202             /* Global variable */
203             g_defdata (CF_EXTERNAL, Expr->Name, Expr->Val);
204             break;
205
206         case E_LOC_STATIC:
207         case E_LOC_LITERAL:
208             /* Static variable or literal in the literal pool */
209             g_defdata (CF_STATIC, Expr->Name, Expr->Val);
210             break;
211
212         case E_LOC_REGISTER:
213             /* Register variable. Taking the address is usually not
214              * allowed.
215              */
216             if (IS_Get (&AllowRegVarAddr) == 0) {
217                 Error ("Cannot take the address of a register variable");
218             }
219             g_defdata (CF_REGVAR, Expr->Name, Expr->Val);
220             break;
221
222         default:
223             Internal ("Unknown constant type: 0x%04X", ED_GetLoc (Expr));
224     }
225 }
226
227
228
229 static void LoadConstant (unsigned Flags, ExprDesc* Expr)
230 /* Load the primary register with some constant value. */
231 {
232     switch (ED_GetLoc (Expr)) {
233
234         case E_LOC_ABS:
235             /* Number constant */
236             g_getimmed (Flags | TypeOf (Expr->Type) | CF_CONST, Expr->Val, 0);
237             break;
238
239         case E_LOC_GLOBAL:
240             /* Global symbol, load address */
241             g_getimmed ((Flags | CF_EXTERNAL) & ~CF_CONST, Expr->Name, Expr->Val);
242             break;
243
244         case E_LOC_STATIC:
245         case E_LOC_LITERAL:
246             /* Static symbol or literal, load address */
247             g_getimmed ((Flags | CF_STATIC) & ~CF_CONST, Expr->Name, Expr->Val);
248             break;
249
250         case E_LOC_REGISTER:
251             /* Register variable. Taking the address is usually not
252              * allowed.
253              */
254             if (IS_Get (&AllowRegVarAddr) == 0) {
255                 Error ("Cannot take the address of a register variable");
256             }
257             g_getimmed ((Flags | CF_REGVAR) & ~CF_CONST, Expr->Name, Expr->Val);
258
259         case E_LOC_STACK:
260             g_leasp (Expr->Val);
261             break;
262
263         default:
264             Internal ("Unknown constant type: %04X", Expr->Flags);
265     }
266 }
267
268
269
270 static int kcalc (token_t tok, long val1, long val2)
271 /* Calculate an operation with left and right operand constant. */
272 {
273     switch (tok) {
274         case TOK_EQ:
275             return (val1 == val2);
276         case TOK_NE:
277             return (val1 != val2);
278         case TOK_LT:
279             return (val1 < val2);
280         case TOK_LE:
281             return (val1 <= val2);
282         case TOK_GE:
283             return (val1 >= val2);
284         case TOK_GT:
285             return (val1 > val2);
286         case TOK_OR:
287             return (val1 | val2);
288         case TOK_XOR:
289             return (val1 ^ val2);
290         case TOK_AND:
291             return (val1 & val2);
292         case TOK_SHR:
293             return (val1 >> val2);
294         case TOK_SHL:
295             return (val1 << val2);
296         case TOK_STAR:
297             return (val1 * val2);
298         case TOK_DIV:
299             if (val2 == 0) {
300                 Error ("Division by zero");
301                 return 0x7FFFFFFF;
302             }
303             return (val1 / val2);
304         case TOK_MOD:
305             if (val2 == 0) {
306                 Error ("Modulo operation with zero");
307                 return 0;
308             }
309             return (val1 % val2);
310         default:
311             Internal ("kcalc: got token 0x%X\n", tok);
312             return 0;
313     }
314 }
315
316
317
318 static const GenDesc* FindGen (token_t Tok, const GenDesc* Table)
319 /* Find a token in a generator table */
320 {
321     while (Table->Tok != TOK_INVALID) {
322         if (Table->Tok == Tok) {
323             return Table;
324         }
325         ++Table;
326     }
327     return 0;
328 }
329
330
331
332 static int TypeSpecAhead (void)
333 /* Return true if some sort of type is waiting (helper for cast and sizeof()
334  * in hie10).
335  */
336 {
337     SymEntry* Entry;
338
339     /* There's a type waiting if:
340      *
341      * We have an opening paren, and
342      *   a.  the next token is a type, or
343      *   b.  the next token is a type qualifier, or
344      *   c.  the next token is a typedef'd type
345      */
346     return CurTok.Tok == TOK_LPAREN && (
347            TokIsType (&NextTok)                         ||
348            TokIsTypeQual (&NextTok)                     ||
349            (NextTok.Tok  == TOK_IDENT                   &&
350            (Entry = FindSym (NextTok.Ident)) != 0       &&
351            SymIsTypeDef (Entry)));
352 }
353
354
355
356 void PushAddr (const ExprDesc* Expr)
357 /* If the expression contains an address that was somehow evaluated,
358  * push this address on the stack. This is a helper function for all
359  * sorts of implicit or explicit assignment functions where the lvalue
360  * must be saved if it's not constant, before evaluating the rhs.
361  */
362 {
363     /* Get the address on stack if needed */
364     if (ED_IsLocExpr (Expr)) {
365         /* Push the address (always a pointer) */
366         g_push (CF_PTR, 0);
367     }
368 }
369
370
371
372 /*****************************************************************************/
373 /*                                   code                                    */
374 /*****************************************************************************/
375
376
377
378 void ExprLoad (unsigned Flags, ExprDesc* Expr)
379 /* Place the result of an expression into the primary register if it is not
380  * already there.
381  */
382 {
383     if (ED_IsLVal (Expr)) {
384
385         /* Dereferenced lvalue */
386         Flags |= TypeOf (Expr->Type);
387         if (Expr->Test & E_FORCETEST) {
388             Flags |= CF_TEST;
389             Expr->Test &= ~E_FORCETEST;
390         }
391
392         switch (ED_GetLoc (Expr)) {
393
394             case E_LOC_ABS:
395                 /* Absolute: numeric address or const */
396                 g_getstatic (Flags | CF_ABSOLUTE, Expr->Val, 0);
397                 break;
398
399             case E_LOC_GLOBAL:
400                 /* Global variable */
401                 g_getstatic (Flags | CF_EXTERNAL, Expr->Name, Expr->Val);
402                 break;
403
404             case E_LOC_STATIC:
405             case E_LOC_LITERAL:
406                 /* Static variable or literal in the literal pool */
407                 g_getstatic (Flags | CF_STATIC, Expr->Name, Expr->Val);
408                 break;
409
410             case E_LOC_REGISTER:
411                 /* Register variable */
412                 g_getstatic (Flags | CF_REGVAR, Expr->Name, Expr->Val);
413                 break;
414
415             case E_LOC_STACK:
416                 /* Value on the stack */
417                 g_getlocal (Flags, Expr->Val);
418                 break;
419
420             case E_LOC_PRIMARY:
421                 /* The primary register - just test if necessary */
422                 if (Flags & CF_TEST) {
423                     g_test (Flags);
424                 }
425                 break;
426
427             case E_LOC_EXPR:
428                 /* Reference to address in primary with offset in Expr */
429                 g_getind (Flags, Expr->Val);
430                 break;
431
432             default:
433                 Internal ("Invalid location in ExprLoad: 0x%04X", ED_GetLoc (Expr));
434         }
435
436     } else {
437         /* An rvalue */
438         if (ED_IsLocExpr (Expr)) {
439             if (Expr->Val != 0) {
440                 /* We have an expression in the primary plus a constant
441                  * offset. Adjust the value in the primary accordingly.
442                  */
443                 Flags |= TypeOf (Expr->Type);
444                 g_inc (Flags | CF_CONST, Expr->Val);
445             }
446         } else {
447             /* Constant of some sort, load it into the primary */
448             LoadConstant (Flags, Expr);
449         }
450
451         /* Are we testing this value? */
452         if (Expr->Test & E_FORCETEST) {
453             /* Yes, force a test */
454             Flags |= TypeOf (Expr->Type);
455             g_test (Flags);
456             Expr->Test &= ~E_FORCETEST;
457         }
458     }
459 }
460
461
462
463 static unsigned FunctionParamList (FuncDesc* Func)
464 /* Parse a function parameter list and pass the parameters to the called
465  * function. Depending on several criteria this may be done by just pushing
466  * each parameter separately, or creating the parameter frame once and then
467  * storing into this frame.
468  * The function returns the size of the parameters pushed.
469  */
470 {
471     ExprDesc Expr;
472
473     /* Initialize variables */
474     SymEntry* Param       = 0;  /* Keep gcc silent */
475     unsigned  ParamSize   = 0;  /* Size of parameters pushed */
476     unsigned  ParamCount  = 0;  /* Number of parameters pushed */
477     unsigned  FrameSize   = 0;  /* Size of parameter frame */
478     unsigned  FrameParams = 0;  /* Number of params in frame */
479     int       FrameOffs   = 0;  /* Offset into parameter frame */
480     int       Ellipsis    = 0;  /* Function is variadic */
481
482     /* As an optimization, we may allocate the complete parameter frame at
483      * once instead of pushing each parameter as it comes. We may do that,
484      * if...
485      *
486      *  - optimizations that increase code size are enabled (allocating the
487      *    stack frame at once gives usually larger code).
488      *  - we have more than one parameter to push (don't count the last param
489      *    for __fastcall__ functions).
490      *
491      * The FrameSize variable will contain a value > 0 if storing into a frame
492      * (instead of pushing) is enabled.
493      *
494      */
495     if (CodeSizeFactor >= 200) {
496
497         /* Calculate the number and size of the parameters */
498         FrameParams = Func->ParamCount;
499         FrameSize   = Func->ParamSize;
500         if (FrameParams > 0 && (Func->Flags & FD_FASTCALL) != 0) {
501             /* Last parameter is not pushed */
502             FrameSize -= CheckedSizeOf (Func->LastParam->Type);
503             --FrameParams;
504         }
505
506         /* Do we have more than one parameter in the frame? */
507         if (FrameParams > 1) {
508             /* Okeydokey, setup the frame */
509             FrameOffs = StackPtr;
510             g_space (FrameSize);
511             StackPtr -= FrameSize;
512         } else {
513             /* Don't use a preallocated frame */
514             FrameSize = 0;
515         }
516     }
517
518     /* Parse the actual parameter list */
519     while (CurTok.Tok != TOK_RPAREN) {
520
521         unsigned Flags;
522
523         /* Count arguments */
524         ++ParamCount;
525
526         /* Fetch the pointer to the next argument, check for too many args */
527         if (ParamCount <= Func->ParamCount) {
528             /* Beware: If there are parameters with identical names, they
529              * cannot go into the same symbol table, which means that in this
530              * case of errorneous input, the number of nodes in the symbol
531              * table and ParamCount are NOT equal. We have to handle this case
532              * below to avoid segmentation violations. Since we know that this
533              * problem can only occur if there is more than one parameter,
534              * we will just use the last one.
535              */
536             if (ParamCount == 1) {
537                 /* First argument */
538                 Param = Func->SymTab->SymHead;
539             } else if (Param->NextSym != 0) {
540                 /* Next argument */
541                 Param = Param->NextSym;
542                 CHECK ((Param->Flags & SC_PARAM) != 0);
543             }
544         } else if (!Ellipsis) {
545             /* Too many arguments. Do we have an open param list? */
546             if ((Func->Flags & FD_VARIADIC) == 0) {
547                 /* End of param list reached, no ellipsis */
548                 Error ("Too many arguments in function call");
549             }
550             /* Assume an ellipsis even in case of errors to avoid an error
551              * message for each other argument.
552              */
553             Ellipsis = 1;
554         }
555
556         /* Evaluate the parameter expression */
557         hie1 (&Expr);
558
559         /* If we don't have an argument spec, accept anything, otherwise
560          * convert the actual argument to the type needed.
561          */
562         Flags = CF_NONE;
563         if (!Ellipsis) {
564             /* Convert the argument to the parameter type if needed */
565             TypeConversion (&Expr, Param->Type);
566
567             /* If we have a prototype, chars may be pushed as chars */
568             Flags |= CF_FORCECHAR;
569         }
570
571         /* Load the value into the primary if it is not already there */
572         ExprLoad (Flags, &Expr);
573
574         /* Use the type of the argument for the push */
575         Flags |= TypeOf (Expr.Type);
576
577         /* If this is a fastcall function, don't push the last argument */
578         if (ParamCount != Func->ParamCount || (Func->Flags & FD_FASTCALL) == 0) {
579             unsigned ArgSize = sizeofarg (Flags);
580             if (FrameSize > 0) {
581                 /* We have the space already allocated, store in the frame.
582                  * Because of invalid type conversions (that have produced an
583                  * error before), we can end up here with a non aligned stack
584                  * frame. Since no output will be generated anyway, handle
585                  * these cases gracefully instead of doing a CHECK.
586                  */
587                 if (FrameSize >= ArgSize) {
588                     FrameSize -= ArgSize;
589                 } else {
590                     FrameSize = 0;
591                 }
592                 FrameOffs -= ArgSize;
593                 /* Store */
594                 g_putlocal (Flags | CF_NOKEEP, FrameOffs, Expr.Val);
595             } else {
596                 /* Push the argument */
597                 g_push (Flags, Expr.Val);
598             }
599
600             /* Calculate total parameter size */
601             ParamSize += ArgSize;
602         }
603
604         /* Check for end of argument list */
605         if (CurTok.Tok != TOK_COMMA) {
606             break;
607         }
608         NextToken ();
609     }
610
611     /* Check if we had enough parameters */
612     if (ParamCount < Func->ParamCount) {
613         Error ("Too few arguments in function call");
614     }
615
616     /* The function returns the size of all parameters pushed onto the stack.
617      * However, if there are parameters missing (which is an error and was
618      * flagged by the compiler) AND a stack frame was preallocated above,
619      * we would loose track of the stackpointer and generate an internal error
620      * later. So we correct the value by the parameters that should have been
621      * pushed to avoid an internal compiler error. Since an error was
622      * generated before, no code will be output anyway.
623      */
624     return ParamSize + FrameSize;
625 }
626
627
628
629 static void FunctionCall (ExprDesc* Expr)
630 /* Perform a function call. */
631 {
632     FuncDesc*     Func;           /* Function descriptor */
633     int           IsFuncPtr;      /* Flag */
634     int           StdFunc;        /* Standard function index */
635     unsigned      ParamSize;      /* Number of parameter bytes */
636     CodeMark      Mark = 0;       /* Initialize to keep gcc silent */
637     int           PtrOffs = 0;    /* Offset of function pointer on stack */
638     int           IsFastCall = 0; /* True if it's a fast call function */
639     int           PtrOnStack = 0; /* True if a pointer copy is on stack */
640
641     /* Skip the left paren */
642     NextToken ();
643
644     /* Get a pointer to the function descriptor from the type string */
645     Func = GetFuncDesc (Expr->Type);
646
647     /* Handle function pointers transparently */
648     IsFuncPtr = IsTypeFuncPtr (Expr->Type);
649     if (IsFuncPtr) {
650
651         /* Check wether it's a fastcall function that has parameters */
652         IsFastCall = IsFastCallFunc (Expr->Type + 1) && (Func->ParamCount > 0);
653
654         /* Things may be difficult, depending on where the function pointer
655          * resides. If the function pointer is an expression of some sort
656          * (not a local or global variable), we have to evaluate this
657          * expression now and save the result for later. Since calls to
658          * function pointers may be nested, we must save it onto the stack.
659          * For fastcall functions we do also need to place a copy of the
660          * pointer on stack, since we cannot use a/x.
661          */
662         PtrOnStack = IsFastCall || !ED_IsConst (Expr);
663         if (PtrOnStack) {
664
665             /* Not a global or local variable, or a fastcall function. Load
666              * the pointer into the primary and mark it as an expression.
667              */
668             ExprLoad (CF_NONE, Expr);
669             ED_MakeRValExpr (Expr);
670
671             /* Remember the code position */
672             Mark = GetCodePos ();
673
674             /* Push the pointer onto the stack and remember the offset */
675             g_push (CF_PTR, 0);
676             PtrOffs = StackPtr;
677         }
678
679     /* Check for known standard functions and inline them */
680     } else if ((StdFunc = FindStdFunc ((const char*) Expr->Name)) >= 0) {
681
682         /* Inline this function */
683         HandleStdFunc (StdFunc, Func, Expr);
684         return;
685
686     }
687
688     /* Parse the parameter list */
689     ParamSize = FunctionParamList (Func);
690
691     /* We need the closing paren here */
692     ConsumeRParen ();
693
694     /* Special handling for function pointers */
695     if (IsFuncPtr) {
696
697         /* If the function is not a fastcall function, load the pointer to
698          * the function into the primary.
699          */
700         if (!IsFastCall) {
701
702             /* Not a fastcall function - we may use the primary */
703             if (PtrOnStack) {
704                 /* If we have no parameters, the pointer is still in the
705                  * primary. Remove the code to push it and correct the
706                  * stack pointer.
707                  */
708                 if (ParamSize == 0) {
709                     RemoveCode (Mark);
710                     pop (CF_PTR);
711                     PtrOnStack = 0;
712                 } else {
713                     /* Load from the saved copy */
714                     g_getlocal (CF_PTR, PtrOffs);
715                 }
716             } else {
717                 /* Load from original location */
718                 ExprLoad (CF_NONE, Expr);
719             }
720
721             /* Call the function */
722             g_callind (TypeOf (Expr->Type+1), ParamSize, PtrOffs);
723
724         } else {
725
726             /* Fastcall function. We cannot use the primary for the function
727              * pointer and must therefore use an offset to the stack location.
728              * Since fastcall functions may never be variadic, we can use the
729              * index register for this purpose.
730              */
731             g_callind (CF_LOCAL, ParamSize, PtrOffs);
732         }
733
734         /* If we have a pointer on stack, remove it */
735         if (PtrOnStack) {
736             g_space (- (int) sizeofarg (CF_PTR));
737             pop (CF_PTR);
738         }
739
740         /* Skip T_PTR */
741         ++Expr->Type;
742
743     } else {
744
745         /* Normal function */
746         g_call (TypeOf (Expr->Type), (const char*) Expr->Name, ParamSize);
747
748     }
749
750     /* The function result is an rvalue in the primary register */
751     ED_MakeRValExpr (Expr);
752     Expr->Type = GetFuncReturn (Expr->Type);
753 }
754
755
756
757 static void Primary (ExprDesc* E)
758 /* This is the lowest level of the expression parser. */
759 {
760     SymEntry* Sym;
761
762     /* Initialize fields in the expression stucture */
763     ED_Init (E);
764
765     /* Character and integer constants. */
766     if (CurTok.Tok == TOK_ICONST || CurTok.Tok == TOK_CCONST) {
767         E->Flags = E_LOC_ABS | E_RTYPE_RVAL;
768         E->Type  = CurTok.Type;
769         E->Val   = CurTok.IVal;
770         NextToken ();
771         return;
772     }
773
774     /* Process parenthesized subexpression by calling the whole parser
775      * recursively.
776      */
777     if (CurTok.Tok == TOK_LPAREN) {
778         NextToken ();
779         hie0 (E);
780         ConsumeRParen ();
781         return;
782     }
783
784     /* If we run into an identifier in preprocessing mode, we assume that this
785      * is an undefined macro and replace it by a constant value of zero.
786      */
787     if (Preprocessing && CurTok.Tok == TOK_IDENT) {
788         ED_MakeConstAbsInt (E, 0);
789         return;
790     }
791
792     /* All others may only be used if the expression evaluation is not called
793      * recursively by the preprocessor.
794      */
795     if (Preprocessing) {
796         /* Illegal expression in PP mode */
797         Error ("Preprocessor expression expected");
798         ED_MakeConstAbsInt (E, 1);
799         return;
800     }
801
802     switch (CurTok.Tok) {
803
804         case TOK_IDENT:
805             /* Identifier. Get a pointer to the symbol table entry */
806             Sym = E->Sym = FindSym (CurTok.Ident);
807
808             /* Is the symbol known? */
809             if (Sym) {
810
811                 /* We found the symbol - skip the name token */
812                 NextToken ();
813
814                 /* Check for illegal symbol types */
815                 CHECK ((Sym->Flags & SC_LABEL) != SC_LABEL);
816                 if (Sym->Flags & SC_TYPE) {
817                     /* Cannot use type symbols */
818                     Error ("Variable identifier expected");
819                     /* Assume an int type to make E valid */
820                     E->Flags = E_LOC_STACK | E_RTYPE_LVAL;
821                     E->Type  = type_int;
822                     return;
823                 }
824
825                 /* Mark the symbol as referenced */
826                 Sym->Flags |= SC_REF;
827
828                 /* The expression type is the symbol type */
829                 E->Type = Sym->Type;
830
831                 /* Check for legal symbol types */
832                 if ((Sym->Flags & SC_CONST) == SC_CONST) {
833                     /* Enum or some other numeric constant */
834                     E->Flags = E_LOC_ABS | E_RTYPE_RVAL;
835                     E->Val = Sym->V.ConstVal;
836                 } else if ((Sym->Flags & SC_FUNC) == SC_FUNC) {
837                     /* Function */
838                     E->Flags = E_LOC_GLOBAL | E_RTYPE_LVAL;
839                     E->Name = (unsigned long) Sym->Name;
840                 } else if ((Sym->Flags & SC_AUTO) == SC_AUTO) {
841                     /* Local variable. If this is a parameter for a variadic
842                      * function, we have to add some address calculations, and the
843                      * address is not const.
844                      */
845                     if ((Sym->Flags & SC_PARAM) == SC_PARAM && F_IsVariadic (CurrentFunc)) {
846                         /* Variadic parameter */
847                         g_leavariadic (Sym->V.Offs - F_GetParamSize (CurrentFunc));
848                         E->Flags = E_LOC_EXPR | E_RTYPE_LVAL;
849                     } else {
850                         /* Normal parameter */
851                         E->Flags = E_LOC_STACK | E_RTYPE_LVAL;
852                         E->Val = Sym->V.Offs;
853                     }
854                 } else if ((Sym->Flags & SC_REGISTER) == SC_REGISTER) {
855                     /* Register variable, zero page based */
856                     E->Flags = E_LOC_REGISTER | E_RTYPE_LVAL;
857                     E->Name  = Sym->V.R.RegOffs;
858                 } else if ((Sym->Flags & SC_STATIC) == SC_STATIC) {
859                     /* Static variable */
860                     if (Sym->Flags & (SC_EXTERN | SC_STORAGE)) {
861                         E->Flags = E_LOC_GLOBAL | E_RTYPE_LVAL;
862                         E->Name = (unsigned long) Sym->Name;
863                     } else {
864                         E->Flags = E_LOC_STATIC | E_RTYPE_LVAL;
865                         E->Name = Sym->V.Label;
866                     }
867                 } else {
868                     /* Local static variable */
869                     E->Flags = E_LOC_STATIC | E_RTYPE_LVAL;
870                     E->Name  = Sym->V.Offs;
871                 }
872
873                 /* We've made all variables lvalues above. However, this is
874                  * not always correct: An array is actually the address of its
875                  * first element, which is a rvalue, and a function is a
876                  * rvalue, too, because we cannot store anything in a function.
877                  * So fix the flags depending on the type.
878                  */
879                 if (IsTypeArray (E->Type) || IsTypeFunc (E->Type)) {
880                     ED_MakeRVal (E);
881                 }
882
883             } else {
884
885                 /* We did not find the symbol. Remember the name, then skip it */
886                 ident Ident;
887                 strcpy (Ident, CurTok.Ident);
888                 NextToken ();
889
890                 /* IDENT is either an auto-declared function or an undefined variable. */
891                 if (CurTok.Tok == TOK_LPAREN) {
892                     /* Declare a function returning int. For that purpose, prepare a
893                      * function signature for a function having an empty param list
894                      * and returning int.
895                      */
896                     Warning ("Function call without a prototype");
897                     Sym = AddGlobalSym (Ident, GetImplicitFuncType(), SC_EXTERN | SC_REF | SC_FUNC);
898                     E->Type  = Sym->Type;
899                     E->Flags = E_LOC_GLOBAL | E_RTYPE_RVAL;
900                     E->Name  = (unsigned long) Sym->Name;
901                 } else {
902                     /* Undeclared Variable */
903                     Sym = AddLocalSym (Ident, type_int, SC_AUTO | SC_REF, 0);
904                     E->Flags = E_LOC_STACK | E_RTYPE_LVAL;
905                     E->Type = type_int;
906                     Error ("Undefined symbol: `%s'", Ident);
907                 }
908
909             }
910             break;
911
912         case TOK_SCONST:
913             /* String literal */
914             E->Type  = GetCharArrayType (GetLiteralPoolOffs () - CurTok.IVal);
915             E->Flags = E_LOC_LITERAL | E_RTYPE_RVAL;
916             E->Val   = CurTok.IVal;
917             E->Name  = LiteralPoolLabel;
918             NextToken ();
919             break;
920
921         case TOK_ASM:
922             /* ASM statement */
923             AsmStatement ();
924             E->Flags = E_LOC_EXPR | E_RTYPE_RVAL;
925             E->Type  = type_void;
926             break;
927
928         case TOK_A:
929             /* Register pseudo variable */
930             E->Type  = type_uchar;
931             E->Flags = E_LOC_PRIMARY | E_RTYPE_LVAL;
932             NextToken ();
933             break;
934
935         case TOK_AX:
936             /* Register pseudo variable */
937             E->Type  = type_uint;
938             E->Flags = E_LOC_PRIMARY | E_RTYPE_LVAL;
939             NextToken ();
940             break;
941
942         case TOK_EAX:
943             /* Register pseudo variable */
944             E->Type  = type_ulong;
945             E->Flags = E_LOC_PRIMARY | E_RTYPE_LVAL;
946             NextToken ();
947             break;
948
949         default:
950             /* Illegal primary. */
951             Error ("Expression expected");
952             ED_MakeConstAbsInt (E, 1);
953             break;
954     }
955 }
956
957
958
959 static void ArrayRef (ExprDesc* Expr)
960 /* Handle an array reference */
961 {
962     int         ConstBaseAddr;
963     ExprDesc    SubScript;
964     CodeMark    Mark1;
965     CodeMark    Mark2;
966     type*       ElementType;
967     type*       tptr1;
968
969
970     /* Skip the bracket */
971     NextToken ();
972
973     /* Get the type of left side */
974     tptr1 = Expr->Type;
975
976     /* We can apply a special treatment for arrays that have a const base
977      * address. This is true for most arrays and will produce a lot better
978      * code. Check if this is a const base address.
979      */
980     ConstBaseAddr = (ED_IsLocConst (Expr) || ED_IsLocStack (Expr));
981
982     /* If we have a constant base, we delay the address fetch */
983     Mark1 = GetCodePos ();
984     Mark2 = 0;          /* Silence gcc */
985     if (!ConstBaseAddr) {
986         /* Get a pointer to the array into the primary */
987         ExprLoad (CF_NONE, Expr);
988
989         /* Get the array pointer on stack. Do not push more than 16
990          * bit, even if this value is greater, since we cannot handle
991          * other than 16bit stuff when doing indexing.
992          */
993         Mark2 = GetCodePos ();
994         g_push (CF_PTR, 0);
995     }
996
997     /* TOS now contains ptr to array elements. Get the subscript. */
998     ExprWithCheck (hie0, &SubScript);
999
1000     /* Check the types of array and subscript. We can either have a
1001      * pointer/array to the left, in which case the subscript must be of an
1002      * integer type, or we have an integer to the left, in which case the
1003      * subscript must be a pointer/array.
1004      * Since we do the necessary checking here, we can rely later on the
1005      * correct types.
1006      */
1007     if (IsClassPtr (Expr->Type)) {
1008         if (!IsClassInt (SubScript.Type))  {
1009             Error ("Array subscript is not an integer");
1010             /* To avoid any compiler errors, make the expression a valid int */
1011             ED_MakeConstAbsInt (&SubScript, 0);
1012         }
1013         ElementType = Indirect (Expr->Type);
1014     } else if (IsClassInt (Expr->Type)) {
1015         if (!IsClassPtr (SubScript.Type)) {
1016             Error ("Subscripted value is neither array nor pointer");
1017             /* To avoid compiler errors, make the subscript a char[] at
1018              * address 0.
1019              */
1020             ED_MakeConstAbs (&SubScript, 0, GetCharArrayType (1));
1021         }
1022         ElementType = Indirect (SubScript.Type);
1023     } else {
1024         Error ("Cannot subscript");
1025         /* To avoid compiler errors, fake both the array and the subscript, so
1026          * we can just proceed.
1027          */
1028         ED_MakeConstAbs (Expr, 0, GetCharArrayType (1));
1029         ED_MakeConstAbsInt (&SubScript, 0);
1030         ElementType = Indirect (Expr->Type);
1031     }
1032
1033     /* Check if the subscript is constant absolute value */
1034     if (ED_IsConstAbs (&SubScript)) {
1035
1036         /* The array subscript is a numeric constant. If we had pushed the
1037          * array base address onto the stack before, we can remove this value,
1038          * since we can generate expression+offset.
1039          */
1040         if (!ConstBaseAddr) {
1041             RemoveCode (Mark2);
1042             pop (CF_PTR);
1043         } else {
1044             /* Get an array pointer into the primary */
1045             ExprLoad (CF_NONE, Expr);
1046         }
1047
1048         if (IsClassPtr (Expr->Type)) {
1049
1050             /* Lhs is pointer/array. Scale the subscript value according to
1051              * the element size.
1052              */
1053             SubScript.Val *= CheckedSizeOf (ElementType);
1054
1055             /* Remove the address load code */
1056             RemoveCode (Mark1);
1057
1058             /* In case of an array, we can adjust the offset of the expression
1059              * already in Expr. If the base address was a constant, we can even
1060              * remove the code that loaded the address into the primary.
1061              */
1062             if (IsTypeArray (Expr->Type)) {
1063
1064                 /* Adjust the offset */
1065                 Expr->Val += SubScript.Val;
1066
1067             } else {
1068
1069                 /* It's a pointer, so we do have to load it into the primary
1070                  * first (if it's not already there).
1071                  */
1072                 if (ConstBaseAddr) {
1073                     ExprLoad (CF_NONE, Expr);
1074                     ED_MakeRValExpr (Expr);
1075                 }
1076
1077                 /* Use the offset */
1078                 Expr->Val = SubScript.Val;
1079             }
1080
1081         } else {
1082
1083             /* Scale the rhs value according to the element type */
1084             g_scale (TypeOf (tptr1), CheckedSizeOf (ElementType));
1085
1086             /* Add the subscript. Since arrays are indexed by integers,
1087              * we will ignore the true type of the subscript here and
1088              * use always an int. #### Use offset but beware of ExprLoad!
1089              */
1090             g_inc (CF_INT | CF_CONST, SubScript.Val);
1091
1092         }
1093
1094     } else {
1095
1096         /* Array subscript is not constant. Load it into the primary */
1097         Mark2 = GetCodePos ();
1098         ExprLoad (CF_NONE, &SubScript);
1099
1100         /* Do scaling */
1101         if (IsClassPtr (Expr->Type)) {
1102
1103             /* Indexing is based on unsigneds, so we will just use the integer
1104              * portion of the index (which is in (e)ax, so there's no further
1105              * action required).
1106              */
1107             g_scale (CF_INT, CheckedSizeOf (ElementType));
1108
1109         } else {
1110
1111             /* Get the int value on top. If we come here, we're sure, both
1112              * values are 16 bit (the first one was truncated if necessary
1113              * and the second one is a pointer). Note: If ConstBaseAddr is
1114              * true, we don't have a value on stack, so to "swap" both, just
1115              * push the subscript.
1116              */
1117             if (ConstBaseAddr) {
1118                 g_push (CF_INT, 0);
1119                 ExprLoad (CF_NONE, Expr);
1120                 ConstBaseAddr = 0;
1121             } else {
1122                 g_swap (CF_INT);
1123             }
1124
1125             /* Scale it */
1126             g_scale (TypeOf (tptr1), CheckedSizeOf (ElementType));
1127
1128         }
1129
1130         /* The offset is now in the primary register. It we didn't have a
1131          * constant base address for the lhs, the lhs address is already
1132          * on stack, and we must add the offset. If the base address was
1133          * constant, we call special functions to add the address to the
1134          * offset value.
1135          */
1136         if (!ConstBaseAddr) {
1137
1138             /* The array base address is on stack and the subscript is in the
1139              * primary. Add both.
1140              */
1141             g_add (CF_INT, 0);
1142
1143         } else {
1144
1145             /* The subscript is in the primary, and the array base address is
1146              * in Expr. If the subscript has itself a constant address, it is
1147              * often a better idea to reverse again the order of the
1148              * evaluation. This will generate better code if the subscript is
1149              * a byte sized variable. But beware: This is only possible if the
1150              * subscript was not scaled, that is, if this was a byte array
1151              * or pointer.
1152              */
1153             if ((ED_IsLocConst (&SubScript) || ED_IsLocStack (&SubScript)) &&
1154                 CheckedSizeOf (ElementType) == SIZEOF_CHAR) {
1155
1156                 unsigned Flags;
1157
1158                 /* Reverse the order of evaluation */
1159                 if (CheckedSizeOf (SubScript.Type) == SIZEOF_CHAR) {
1160                     Flags = CF_CHAR;
1161                 } else {
1162                     Flags = CF_INT;
1163                 }
1164                 RemoveCode (Mark2);
1165
1166                 /* Get a pointer to the array into the primary. */
1167                 ExprLoad (CF_NONE, Expr);
1168
1169                 /* Add the variable */
1170                 if (ED_IsLocStack (&SubScript)) {
1171                     g_addlocal (Flags, SubScript.Val);
1172                 } else {
1173                     Flags |= GlobalModeFlags (SubScript.Flags);
1174                     g_addstatic (Flags, SubScript.Name, SubScript.Val);
1175                 }
1176             } else {
1177                 if (ED_IsLocAbs (Expr)) {
1178                     /* Constant numeric address. Just add it */
1179                     g_inc (CF_INT, Expr->Val);
1180                 } else if (ED_IsLocStack (Expr)) {
1181                     /* Base address is a local variable address */
1182                     if (IsTypeArray (Expr->Type)) {
1183                         g_addaddr_local (CF_INT, Expr->Val);
1184                     } else {
1185                         g_addlocal (CF_PTR, Expr->Val);
1186                     }
1187                 } else {
1188                     /* Base address is a static variable address */
1189                     unsigned Flags = CF_INT | GlobalModeFlags (Expr->Flags);
1190                     if (IsTypeArray (Expr->Type)) {
1191                         g_addaddr_static (Flags, Expr->Name, Expr->Val);
1192                     } else {
1193                         g_addstatic (Flags, Expr->Name, Expr->Val);
1194                     }
1195                 }
1196             }
1197
1198
1199         }
1200
1201         /* The result is an expression in the primary */
1202         ED_MakeRValExpr (Expr);
1203
1204     }
1205
1206     /* Result is of element type */
1207     Expr->Type = ElementType;
1208
1209     /* An array element is actually a variable. So the rules for variables
1210      * with respect to the reference type apply: If it's an array, it is
1211      * a rvalue, otherwise it's an lvalue. (A function would also be a rvalue,
1212      * but an array cannot contain functions).
1213      */
1214     if (IsTypeArray (Expr->Type)) {
1215         ED_MakeRVal (Expr);
1216     } else {
1217         ED_MakeLVal (Expr);
1218     }
1219
1220     /* Consume the closing bracket */
1221     ConsumeRBrack ();
1222 }
1223
1224
1225
1226 static void StructRef (ExprDesc* Expr)
1227 /* Process struct field after . or ->. */
1228 {
1229     ident Ident;
1230     SymEntry* Field;
1231
1232     /* Skip the token and check for an identifier */
1233     NextToken ();
1234     if (CurTok.Tok != TOK_IDENT) {
1235         Error ("Identifier expected");
1236         Expr->Type = type_int;
1237         return;
1238     }
1239
1240     /* Get the symbol table entry and check for a struct field */
1241     strcpy (Ident, CurTok.Ident);
1242     NextToken ();
1243     Field = FindStructField (Expr->Type, Ident);
1244     if (Field == 0) {
1245         Error ("Struct/union has no field named `%s'", Ident);
1246         Expr->Type = type_int;
1247         return;
1248     }
1249
1250     /* If we have a struct pointer that is an lvalue and not already in the
1251      * primary, load it now.
1252      */
1253     if (ED_IsLVal (Expr) && IsTypePtr (Expr->Type)) {
1254
1255         /* Load into the primary */
1256         ExprLoad (CF_NONE, Expr);
1257
1258         /* Make it an lvalue expression */
1259         ED_MakeLValExpr (Expr);
1260     }
1261
1262     /* Set the struct field offset */
1263     Expr->Val += Field->V.Offs;
1264
1265     /* The type is now the type of the field */
1266     Expr->Type = Field->Type;
1267
1268     /* An struct member is actually a variable. So the rules for variables
1269      * with respect to the reference type apply: If it's an array, it is
1270      * a rvalue, otherwise it's an lvalue. (A function would also be a rvalue,
1271      * but a struct field cannot be a function).
1272      */
1273     if (IsTypeArray (Expr->Type)) {
1274         ED_MakeRVal (Expr);
1275     } else {
1276         ED_MakeLVal (Expr);
1277     }
1278 }
1279
1280
1281
1282 static void hie11 (ExprDesc *Expr)
1283 /* Handle compound types (structs and arrays) */
1284 {
1285     /* Evaluate the lhs */
1286     Primary (Expr);
1287
1288     /* Check for a rhs */
1289     while (CurTok.Tok == TOK_LBRACK || CurTok.Tok == TOK_LPAREN ||
1290            CurTok.Tok == TOK_DOT    || CurTok.Tok == TOK_PTR_REF) {
1291
1292         switch (CurTok.Tok) {
1293
1294             case TOK_LBRACK:
1295                 /* Array reference */
1296                 ArrayRef (Expr);
1297                 break;
1298
1299             case TOK_LPAREN:
1300                 /* Function call. */
1301                 if (!IsTypeFunc (Expr->Type) && !IsTypeFuncPtr (Expr->Type)) {
1302                     /* Not a function */
1303                     Error ("Illegal function call");
1304                     /* Force the type to be a implicitly defined function, one
1305                      * returning an int and taking any number of arguments.
1306                      * Since we don't have a name, place it at absolute address
1307                      * zero.
1308                      */
1309                     ED_MakeConstAbs (Expr, 0, GetImplicitFuncType ());
1310                 }
1311                 /* Call the function */
1312                 FunctionCall (Expr);
1313                 break;
1314
1315             case TOK_DOT:
1316                 if (!IsClassStruct (Expr->Type)) {
1317                     Error ("Struct expected");
1318                 }
1319                 StructRef (Expr);
1320                 break;
1321
1322             case TOK_PTR_REF:
1323                 /* If we have an array, convert it to pointer to first element */
1324                 if (IsTypeArray (Expr->Type)) {
1325                     Expr->Type = ArrayToPtr (Expr->Type);
1326                 }
1327                 if (!IsClassPtr (Expr->Type) || !IsClassStruct (Indirect (Expr->Type))) {
1328                     Error ("Struct pointer expected");
1329                 }
1330                 StructRef (Expr);
1331                 break;
1332
1333             default:
1334                 Internal ("Invalid token in hie11: %d", CurTok.Tok);
1335
1336         }
1337     }
1338 }
1339
1340
1341
1342 void Store (ExprDesc* Expr, const type* StoreType)
1343 /* Store the primary register into the location denoted by Expr. If StoreType
1344  * is given, use this type when storing instead of Expr->Type. If StoreType
1345  * is NULL, use Expr->Type instead.
1346  */
1347 {
1348     unsigned Flags;
1349
1350     /* If StoreType was not given, use Expr->Type instead */
1351     if (StoreType == 0) {
1352         StoreType = Expr->Type;
1353     }
1354
1355     /* Prepare the code generator flags */
1356     Flags = TypeOf (StoreType);
1357     if (Expr->Test) {
1358         /* Testing the value */
1359         Flags |= CF_TEST;
1360     }
1361
1362     /* Do the store depending on the location */
1363     switch (ED_GetLoc (Expr)) {
1364
1365         case E_LOC_ABS:
1366             /* Absolute: numeric address or const */
1367             g_putstatic (Flags | CF_ABSOLUTE, Expr->Val, 0);
1368             break;
1369
1370         case E_LOC_GLOBAL:
1371             /* Global variable */
1372             g_putstatic (Flags | CF_EXTERNAL, Expr->Name, Expr->Val);
1373             break;
1374
1375         case E_LOC_STATIC:
1376         case E_LOC_LITERAL:
1377             /* Static variable or literal in the literal pool */
1378             g_putstatic (Flags | CF_STATIC, Expr->Name, Expr->Val);
1379             break;
1380
1381         case E_LOC_REGISTER:
1382             /* Register variable */
1383             g_putstatic (Flags | CF_REGVAR, Expr->Name, Expr->Val);
1384             break;
1385
1386         case E_LOC_STACK:
1387             /* Value on the stack */
1388             g_putlocal (Flags, Expr->Val, 0);
1389             break;
1390
1391         case E_LOC_PRIMARY:
1392             /* The primary register (value is already there) */
1393             /* ### Do we need a test here if the flag is set? */
1394             break;
1395
1396         case E_LOC_EXPR:
1397             /* An expression in the primary register */
1398             g_putind (Flags, Expr->Val);
1399             break;
1400
1401         default:
1402             Internal ("Invalid location in Store(): 0x%04X", ED_GetLoc (Expr));
1403     }
1404
1405     /* Assume that each one of the stores will invalidate CC */
1406     Expr->Test &= ~E_CC;
1407 }
1408
1409
1410
1411 static void PreInc (ExprDesc* Expr)
1412 /* Handle the preincrement operators */
1413 {
1414     unsigned Flags;
1415     unsigned long Val;
1416
1417     /* Skip the operator token */
1418     NextToken ();
1419
1420     /* Evaluate the expression and check that it is an lvalue */
1421     hie10 (Expr);
1422     if (!ED_IsLVal (Expr)) {
1423         Error ("Invalid lvalue");
1424         return;
1425     }
1426
1427     /* Get the data type */
1428     Flags = TypeOf (Expr->Type) | CF_FORCECHAR | CF_CONST;
1429
1430     /* Get the increment value in bytes */
1431     Val = IsTypePtr (Expr->Type)? CheckedPSizeOf (Expr->Type) : 1;
1432
1433     /* Check the location of the data */
1434     switch (ED_GetLoc (Expr)) {
1435
1436         case E_LOC_ABS:
1437             /* Absolute: numeric address or const */
1438             g_addeqstatic (Flags | CF_ABSOLUTE, Expr->Val, 0, Val);
1439             break;
1440
1441         case E_LOC_GLOBAL:
1442             /* Global variable */
1443             g_addeqstatic (Flags | CF_EXTERNAL, Expr->Name, Expr->Val, Val);
1444             break;
1445
1446         case E_LOC_STATIC:
1447         case E_LOC_LITERAL:
1448             /* Static variable or literal in the literal pool */
1449             g_addeqstatic (Flags | CF_STATIC, Expr->Name, Expr->Val, Val);
1450             break;
1451
1452         case E_LOC_REGISTER:
1453             /* Register variable */
1454             g_addeqstatic (Flags | CF_REGVAR, Expr->Name, Expr->Val, Val);
1455             break;
1456
1457         case E_LOC_STACK:
1458             /* Value on the stack */
1459             g_addeqlocal (Flags, Expr->Val, Val);
1460             break;
1461
1462         case E_LOC_PRIMARY:
1463             /* The primary register */
1464             g_inc (Flags, Val);
1465             break;
1466
1467         case E_LOC_EXPR:
1468             /* An expression in the primary register */
1469             g_addeqind (Flags, Expr->Val, Val);
1470             break;
1471
1472         default:
1473             Internal ("Invalid location in PreInc(): 0x%04X", ED_GetLoc (Expr));
1474     }
1475
1476     /* Result is an expression, no reference */
1477     ED_MakeRValExpr (Expr);
1478 }
1479
1480
1481
1482 static void PreDec (ExprDesc* Expr)
1483 /* Handle the predecrement operators */
1484 {
1485     unsigned Flags;
1486     unsigned long Val;
1487
1488     /* Skip the operator token */
1489     NextToken ();
1490
1491     /* Evaluate the expression and check that it is an lvalue */
1492     hie10 (Expr);
1493     if (!ED_IsLVal (Expr)) {
1494         Error ("Invalid lvalue");
1495         return;
1496     }
1497
1498     /* Get the data type */
1499     Flags = TypeOf (Expr->Type) | CF_FORCECHAR | CF_CONST;
1500
1501     /* Get the increment value in bytes */
1502     Val = IsTypePtr (Expr->Type)? CheckedPSizeOf (Expr->Type) : 1;
1503
1504     /* Check the location of the data */
1505     switch (ED_GetLoc (Expr)) {
1506
1507         case E_LOC_ABS:
1508             /* Absolute: numeric address or const */
1509             g_subeqstatic (Flags | CF_ABSOLUTE, Expr->Val, 0, Val);
1510             break;
1511
1512         case E_LOC_GLOBAL:
1513             /* Global variable */
1514             g_subeqstatic (Flags | CF_EXTERNAL, Expr->Name, Expr->Val, Val);
1515             break;
1516
1517         case E_LOC_STATIC:
1518         case E_LOC_LITERAL:
1519             /* Static variable or literal in the literal pool */
1520             g_subeqstatic (Flags | CF_STATIC, Expr->Name, Expr->Val, Val);
1521             break;
1522
1523         case E_LOC_REGISTER:
1524             /* Register variable */
1525             g_subeqstatic (Flags | CF_REGVAR, Expr->Name, Expr->Val, Val);
1526             break;
1527
1528         case E_LOC_STACK:
1529             /* Value on the stack */
1530             g_subeqlocal (Flags, Expr->Val, Val);
1531             break;
1532
1533         case E_LOC_PRIMARY:
1534             /* The primary register */
1535             g_inc (Flags, Val);
1536             break;
1537
1538         case E_LOC_EXPR:
1539             /* An expression in the primary register */
1540             g_subeqind (Flags, Expr->Val, Val);
1541             break;
1542
1543         default:
1544             Internal ("Invalid location in PreDec(): 0x%04X", ED_GetLoc (Expr));
1545     }
1546
1547     /* Result is an expression, no reference */
1548     ED_MakeRValExpr (Expr);
1549 }
1550
1551
1552
1553 static void PostIncDec (ExprDesc* Expr, void (*inc) (unsigned, unsigned long))
1554 /* Handle i-- and i++ */
1555 {
1556     unsigned Flags;
1557
1558     NextToken ();
1559
1560     /* The expression to increment must be an lvalue */
1561     if (!ED_IsLVal (Expr)) {
1562         Error ("Invalid lvalue");
1563         return;
1564     }
1565
1566     /* Get the data type */
1567     Flags = TypeOf (Expr->Type);
1568
1569     /* Push the address if needed */
1570     PushAddr (Expr);
1571
1572     /* Fetch the value and save it (since it's the result of the expression) */
1573     ExprLoad (CF_NONE, Expr);
1574     g_save (Flags | CF_FORCECHAR);
1575
1576     /* If we have a pointer expression, increment by the size of the type */
1577     if (IsTypePtr (Expr->Type)) {
1578         inc (Flags | CF_CONST | CF_FORCECHAR, CheckedSizeOf (Expr->Type + 1));
1579     } else {
1580         inc (Flags | CF_CONST | CF_FORCECHAR, 1);
1581     }
1582
1583     /* Store the result back */
1584     Store (Expr, 0);
1585
1586     /* Restore the original value in the primary register */
1587     g_restore (Flags | CF_FORCECHAR);
1588
1589     /* The result is always an expression, no reference */
1590     ED_MakeRValExpr (Expr);
1591 }
1592
1593
1594
1595 static void UnaryOp (ExprDesc* Expr)
1596 /* Handle unary -/+ and ~ */
1597 {
1598     unsigned Flags;
1599
1600     /* Remember the operator token and skip it */
1601     token_t Tok = CurTok.Tok;
1602     NextToken ();
1603
1604     /* Get the expression */
1605     hie10 (Expr);
1606
1607     /* We can only handle integer types */
1608     if (!IsClassInt (Expr->Type)) {
1609         Error ("Argument must have integer type");
1610         ED_MakeConstAbsInt (Expr, 1);
1611     }
1612
1613     /* Check for a constant expression */
1614     if (ED_IsConstAbs (Expr)) {
1615         /* Value is constant */
1616         switch (Tok) {
1617             case TOK_MINUS: Expr->Val = -Expr->Val;     break;
1618             case TOK_PLUS:                              break;
1619             case TOK_COMP:  Expr->Val = ~Expr->Val;     break;
1620             default:        Internal ("Unexpected token: %d", Tok);
1621         }
1622     } else {
1623         /* Value is not constant */
1624         ExprLoad (CF_NONE, Expr);
1625
1626         /* Get the type of the expression */
1627         Flags = TypeOf (Expr->Type);
1628
1629         /* Handle the operation */
1630         switch (Tok) {
1631             case TOK_MINUS: g_neg (Flags);  break;
1632             case TOK_PLUS:                  break;
1633             case TOK_COMP:  g_com (Flags);  break;
1634             default:        Internal ("Unexpected token: %d", Tok);
1635         }
1636
1637         /* The result is a rvalue in the primary */
1638         ED_MakeRValExpr (Expr);
1639     }
1640 }
1641
1642
1643
1644 void hie10 (ExprDesc* Expr)
1645 /* Handle ++, --, !, unary - etc. */
1646 {
1647     unsigned long Size;
1648
1649     switch (CurTok.Tok) {
1650
1651         case TOK_INC:
1652             PreInc (Expr);
1653             break;
1654
1655         case TOK_DEC:
1656             PreDec (Expr);
1657             break;
1658
1659         case TOK_PLUS:
1660         case TOK_MINUS:
1661         case TOK_COMP:
1662             UnaryOp (Expr);
1663             break;
1664
1665         case TOK_BOOL_NOT:
1666             NextToken ();
1667             if (evalexpr (CF_NONE, hie10, Expr) == 0) {
1668                 /* Constant expression */
1669                 Expr->Val = !Expr->Val;
1670             } else {
1671                 g_bneg (TypeOf (Expr->Type));
1672                 ED_MakeRValExpr (Expr);
1673                 Expr->Test |= E_CC;             /* bneg will set cc */
1674             }
1675             break;
1676
1677         case TOK_STAR:
1678             NextToken ();
1679             ExprWithCheck (hie10, Expr);
1680             if (ED_IsLVal (Expr) || !(ED_IsLocConst (Expr) || ED_IsLocStack (Expr))) {
1681                 /* Not a const, load it into the primary and make it a
1682                  * calculated value.
1683                  */
1684                 ExprLoad (CF_NONE, Expr);
1685                 ED_MakeRValExpr (Expr);
1686             }
1687             /* If the expression is already a pointer to function, the
1688              * additional dereferencing operator must be ignored.
1689              */
1690             if (IsTypeFuncPtr (Expr->Type)) {
1691                 /* Expression not storable */
1692                 ED_MakeRVal (Expr);
1693             } else {
1694                 if (IsClassPtr (Expr->Type)) {
1695                     Expr->Type = Indirect (Expr->Type);
1696                 } else {
1697                     Error ("Illegal indirection");
1698                 }
1699                 ED_MakeLVal (Expr);
1700             }
1701             break;
1702
1703         case TOK_AND:
1704             NextToken ();
1705             ExprWithCheck (hie10, Expr);
1706             /* The & operator may be applied to any lvalue, and it may be
1707              * applied to functions, even if they're no lvalues.
1708              */
1709             if (ED_IsRVal (Expr) && !IsTypeFunc (Expr->Type)) {
1710                 /* Allow the & operator with an array */
1711                 if (!IsTypeArray (Expr->Type)) {
1712                     Error ("Illegal address");
1713                 }
1714             } else {
1715                 Expr->Type = PointerTo (Expr->Type);
1716                 ED_MakeRVal (Expr);
1717             }
1718             break;
1719
1720         case TOK_SIZEOF:
1721             NextToken ();
1722             if (TypeSpecAhead ()) {
1723                 type Type[MAXTYPELEN];
1724                 NextToken ();
1725                 Size = CheckedSizeOf (ParseType (Type));
1726                 ConsumeRParen ();
1727             } else {
1728                 /* Remember the output queue pointer */
1729                 CodeMark Mark = GetCodePos ();
1730                 hie10 (Expr);
1731                 Size = CheckedSizeOf (Expr->Type);
1732                 /* Remove any generated code */
1733                 RemoveCode (Mark);
1734             }
1735             ED_MakeConstAbs (Expr, Size, type_size_t);
1736             Expr->Test &= ~E_CC;
1737             break;
1738
1739         default:
1740             if (TypeSpecAhead ()) {
1741
1742                 /* A typecast */
1743                 TypeCast (Expr);
1744
1745             } else {
1746
1747                 /* An expression */
1748                 hie11 (Expr);
1749
1750                 /* Handle post increment */
1751                 if (CurTok.Tok == TOK_INC) {
1752                     PostIncDec (Expr, g_inc);
1753                 } else if (CurTok.Tok == TOK_DEC) {
1754                     PostIncDec (Expr, g_dec);
1755                 }
1756
1757             }
1758             break;
1759     }
1760 }
1761
1762
1763
1764 static void hie_internal (const GenDesc* Ops,   /* List of generators */
1765                           ExprDesc* Expr,
1766                           void (*hienext) (ExprDesc*),
1767                           int* UsedGen)
1768 /* Helper function */
1769 {
1770     ExprDesc Expr2;
1771     CodeMark Mark1;
1772     CodeMark Mark2;
1773     const GenDesc* Gen;
1774     token_t Tok;                        /* The operator token */
1775     unsigned ltype, type;
1776     int rconst;                         /* Operand is a constant */
1777
1778
1779     hienext (Expr);
1780
1781     *UsedGen = 0;
1782     while ((Gen = FindGen (CurTok.Tok, Ops)) != 0) {
1783
1784         /* Tell the caller that we handled it's ops */
1785         *UsedGen = 1;
1786
1787         /* All operators that call this function expect an int on the lhs */
1788         if (!IsClassInt (Expr->Type)) {
1789             Error ("Integer expression expected");
1790         }
1791
1792         /* Remember the operator token, then skip it */
1793         Tok = CurTok.Tok;
1794         NextToken ();
1795
1796         /* Get the lhs on stack */
1797         Mark1 = GetCodePos ();
1798         ltype = TypeOf (Expr->Type);
1799         if (ED_IsConstAbs (Expr)) {
1800             /* Constant value */
1801             Mark2 = GetCodePos ();
1802             g_push (ltype | CF_CONST, Expr->Val);
1803         } else {
1804             /* Value not constant */
1805             ExprLoad (CF_NONE, Expr);
1806             Mark2 = GetCodePos ();
1807             g_push (ltype, 0);
1808         }
1809
1810         /* Get the right hand side */
1811         rconst = (evalexpr (CF_NONE, hienext, &Expr2) == 0);
1812
1813         /* Check the type of the rhs */
1814         if (!IsClassInt (Expr2.Type)) {
1815             Error ("Integer expression expected");
1816         }
1817
1818         /* Check for const operands */
1819         if (ED_IsConstAbs (Expr) && rconst) {
1820
1821             /* Both operands are constant, remove the generated code */
1822             RemoveCode (Mark1);
1823             pop (ltype);
1824
1825             /* Evaluate the result */
1826             Expr->Val = kcalc (Tok, Expr->Val, Expr2.Val);
1827
1828             /* Get the type of the result */
1829             Expr->Type = promoteint (Expr->Type, Expr2.Type);
1830
1831         } else {
1832
1833             /* If the right hand side is constant, and the generator function
1834              * expects the lhs in the primary, remove the push of the primary
1835              * now.
1836              */
1837             unsigned rtype = TypeOf (Expr2.Type);
1838             type = 0;
1839             if (rconst) {
1840                 /* Second value is constant - check for div */
1841                 type |= CF_CONST;
1842                 rtype |= CF_CONST;
1843                 if (Tok == TOK_DIV && Expr2.Val == 0) {
1844                     Error ("Division by zero");
1845                 } else if (Tok == TOK_MOD && Expr2.Val == 0) {
1846                     Error ("Modulo operation with zero");
1847                 }
1848                 if ((Gen->Flags & GEN_NOPUSH) != 0) {
1849                     RemoveCode (Mark2);
1850                     pop (ltype);
1851                     ltype |= CF_REG;    /* Value is in register */
1852                 }
1853             }
1854
1855             /* Determine the type of the operation result. */
1856             type |= g_typeadjust (ltype, rtype);
1857             Expr->Type = promoteint (Expr->Type, Expr2.Type);
1858
1859             /* Generate code */
1860             Gen->Func (type, Expr2.Val);
1861
1862             /* We have a rvalue in the primary now */
1863             ED_MakeRValExpr (Expr);
1864         }
1865     }
1866 }
1867
1868
1869
1870 static void hie_compare (const GenDesc* Ops,    /* List of generators */
1871                          ExprDesc* Expr,
1872                          void (*hienext) (ExprDesc*))
1873 /* Helper function for the compare operators */
1874 {
1875     ExprDesc Expr2;
1876     CodeMark Mark1;
1877     CodeMark Mark2;
1878     const GenDesc* Gen;
1879     token_t tok;                        /* The operator token */
1880     unsigned ltype;
1881     int rconst;                         /* Operand is a constant */
1882
1883
1884     hienext (Expr);
1885
1886     while ((Gen = FindGen (CurTok.Tok, Ops)) != 0) {
1887
1888         /* Remember the operator token, then skip it */
1889         tok = CurTok.Tok;
1890         NextToken ();
1891
1892         /* Get the lhs on stack */
1893         Mark1 = GetCodePos ();
1894         ltype = TypeOf (Expr->Type);
1895         if (ED_IsConstAbs (Expr)) {
1896             /* Constant value */
1897             Mark2 = GetCodePos ();
1898             g_push (ltype | CF_CONST, Expr->Val);
1899         } else {
1900             /* Value not constant */
1901             ExprLoad (CF_NONE, Expr);
1902             Mark2 = GetCodePos ();
1903             g_push (ltype, 0);
1904         }
1905
1906         /* Get the right hand side */
1907         rconst = (evalexpr (CF_NONE, hienext, &Expr2) == 0);
1908
1909         /* Make sure, the types are compatible */
1910         if (IsClassInt (Expr->Type)) {
1911             if (!IsClassInt (Expr2.Type) && !(IsClassPtr(Expr2.Type) && ED_IsNullPtr(Expr))) {
1912                 Error ("Incompatible types");
1913             }
1914         } else if (IsClassPtr (Expr->Type)) {
1915             if (IsClassPtr (Expr2.Type)) {
1916                 /* Both pointers are allowed in comparison if they point to
1917                  * the same type, or if one of them is a void pointer.
1918                  */
1919                 type* left  = Indirect (Expr->Type);
1920                 type* right = Indirect (Expr2.Type);
1921                 if (TypeCmp (left, right) < TC_EQUAL && *left != T_VOID && *right != T_VOID) {
1922                     /* Incomatible pointers */
1923                     Error ("Incompatible types");
1924                 }
1925             } else if (!ED_IsNullPtr (&Expr2)) {
1926                 Error ("Incompatible types");
1927             }
1928         }
1929
1930         /* Check for const operands */
1931         if (ED_IsConstAbs (Expr) && rconst) {
1932
1933             /* Both operands are constant, remove the generated code */
1934             RemoveCode (Mark1);
1935             pop (ltype);
1936
1937             /* Evaluate the result */
1938             Expr->Val = kcalc (tok, Expr->Val, Expr2.Val);
1939
1940         } else {
1941
1942             /* If the right hand side is constant, and the generator function
1943              * expects the lhs in the primary, remove the push of the primary
1944              * now.
1945              */
1946             unsigned flags = 0;
1947             if (rconst) {
1948                 flags |= CF_CONST;
1949                 if ((Gen->Flags & GEN_NOPUSH) != 0) {
1950                     RemoveCode (Mark2);
1951                     pop (ltype);
1952                     ltype |= CF_REG;    /* Value is in register */
1953                 }
1954             }
1955
1956             /* Determine the type of the operation result. If the left
1957              * operand is of type char and the right is a constant, or
1958              * if both operands are of type char, we will encode the
1959              * operation as char operation. Otherwise the default
1960              * promotions are used.
1961              */
1962             if (IsTypeChar (Expr->Type) && (IsTypeChar (Expr2.Type) || rconst)) {
1963                 flags |= CF_CHAR;
1964                 if (IsSignUnsigned (Expr->Type) || IsSignUnsigned (Expr2.Type)) {
1965                     flags |= CF_UNSIGNED;
1966                 }
1967                 if (rconst) {
1968                     flags |= CF_FORCECHAR;
1969                 }
1970             } else {
1971                 unsigned rtype = TypeOf (Expr2.Type) | (flags & CF_CONST);
1972                 flags |= g_typeadjust (ltype, rtype);
1973             }
1974
1975             /* Generate code */
1976             Gen->Func (flags, Expr2.Val);
1977
1978             /* The result is an rvalue in the primary */
1979             ED_MakeRValExpr (Expr);
1980         }
1981
1982         /* Result type is always int */
1983         Expr->Type = type_int;
1984
1985         /* Condition codes are set */
1986         Expr->Test |= E_CC;
1987     }
1988 }
1989
1990
1991
1992 static void hie9 (ExprDesc *Expr)
1993 /* Process * and / operators. */
1994 {
1995     static const GenDesc hie9_ops[] = {
1996         { TOK_STAR,     GEN_NOPUSH,     g_mul   },
1997         { TOK_DIV,      GEN_NOPUSH,     g_div   },
1998         { TOK_MOD,      GEN_NOPUSH,     g_mod   },
1999         { TOK_INVALID,  0,              0       }
2000     };
2001     int UsedGen;
2002
2003     hie_internal (hie9_ops, Expr, hie10, &UsedGen);
2004 }
2005
2006
2007
2008 static void parseadd (ExprDesc* Expr)
2009 /* Parse an expression with the binary plus operator. Expr contains the
2010  * unprocessed left hand side of the expression and will contain the
2011  * result of the expression on return.
2012  */
2013 {
2014     ExprDesc Expr2;
2015     unsigned flags;             /* Operation flags */
2016     CodeMark Mark;              /* Remember code position */
2017     type* lhst;                 /* Type of left hand side */
2018     type* rhst;                 /* Type of right hand side */
2019
2020
2021     /* Skip the PLUS token */
2022     NextToken ();
2023
2024     /* Get the left hand side type, initialize operation flags */
2025     lhst = Expr->Type;
2026     flags = 0;
2027
2028     /* Check for constness on both sides */
2029     if (ED_IsConst (Expr)) {
2030
2031         /* The left hand side is a constant of some sort. Good. Get rhs */
2032         hie9 (&Expr2);
2033         if (ED_IsConstAbs (&Expr2)) {
2034
2035             /* Right hand side is a constant numeric value. Get the rhs type */
2036             rhst = Expr2.Type;
2037
2038             /* Both expressions are constants. Check for pointer arithmetic */
2039             if (IsClassPtr (lhst) && IsClassInt (rhst)) {
2040                 /* Left is pointer, right is int, must scale rhs */
2041                 Expr->Val += Expr2.Val * CheckedPSizeOf (lhst);
2042                 /* Result type is a pointer */
2043             } else if (IsClassInt (lhst) && IsClassPtr (rhst)) {
2044                 /* Left is int, right is pointer, must scale lhs */
2045                 Expr->Val = Expr->Val * CheckedPSizeOf (rhst) + Expr2.Val;
2046                 /* Result type is a pointer */
2047                 Expr->Type = Expr2.Type;
2048             } else if (IsClassInt (lhst) && IsClassInt (rhst)) {
2049                 /* Integer addition */
2050                 Expr->Val += Expr2.Val;
2051                 typeadjust (Expr, &Expr2, 1);
2052             } else {
2053                 /* OOPS */
2054                 Error ("Invalid operands for binary operator `+'");
2055             }
2056
2057         } else {
2058
2059             /* lhs is a constant and rhs is not constant. Load rhs into
2060              * the primary.
2061              */
2062             ExprLoad (CF_NONE, &Expr2);
2063
2064             /* Beware: The check above (for lhs) lets not only pass numeric
2065              * constants, but also constant addresses (labels), maybe even
2066              * with an offset. We have to check for that here.
2067              */
2068
2069             /* First, get the rhs type. */
2070             rhst = Expr2.Type;
2071
2072             /* Setup flags */
2073             if (ED_IsLocAbs (Expr)) {
2074                 /* A numerical constant */
2075                 flags |= CF_CONST;
2076             } else {
2077                 /* Constant address label */
2078                 flags |= GlobalModeFlags (Expr->Flags) | CF_CONSTADDR;
2079             }
2080
2081             /* Check for pointer arithmetic */
2082             if (IsClassPtr (lhst) && IsClassInt (rhst)) {
2083                 /* Left is pointer, right is int, must scale rhs */
2084                 g_scale (CF_INT, CheckedPSizeOf (lhst));
2085                 /* Operate on pointers, result type is a pointer */
2086                 flags |= CF_PTR;
2087                 /* Generate the code for the add */
2088                 if (ED_GetLoc (Expr) == E_LOC_ABS) {
2089                     /* Numeric constant */
2090                     g_inc (flags, Expr->Val);
2091                 } else {
2092                     /* Constant address */
2093                     g_addaddr_static (flags, Expr->Name, Expr->Val);
2094                 }
2095             } else if (IsClassInt (lhst) && IsClassPtr (rhst)) {
2096
2097                 /* Left is int, right is pointer, must scale lhs. */
2098                 unsigned ScaleFactor = CheckedPSizeOf (rhst);
2099
2100                 /* Operate on pointers, result type is a pointer */
2101                 flags |= CF_PTR;
2102                 Expr->Type = Expr2.Type;
2103
2104                 /* Since we do already have rhs in the primary, if lhs is
2105                  * not a numeric constant, and the scale factor is not one
2106                  * (no scaling), we must take the long way over the stack.
2107                  */
2108                 if (ED_IsLocAbs (Expr)) {
2109                     /* Numeric constant, scale lhs */
2110                     Expr->Val *= ScaleFactor;
2111                     /* Generate the code for the add */
2112                     g_inc (flags, Expr->Val);
2113                 } else if (ScaleFactor == 1) {
2114                     /* Constant address but no need to scale */
2115                     g_addaddr_static (flags, Expr->Name, Expr->Val);
2116                 } else {
2117                     /* Constant address that must be scaled */
2118                     g_push (TypeOf (Expr2.Type), 0);    /* rhs --> stack */
2119                     g_getimmed (flags, Expr->Name, Expr->Val);
2120                     g_scale (CF_PTR, ScaleFactor);
2121                     g_add (CF_PTR, 0);
2122                 }
2123             } else if (IsClassInt (lhst) && IsClassInt (rhst)) {
2124                 /* Integer addition */
2125                 flags |= typeadjust (Expr, &Expr2, 1);
2126                 /* Generate the code for the add */
2127                 if (ED_IsLocAbs (Expr)) {
2128                     /* Numeric constant */
2129                     g_inc (flags, Expr->Val);
2130                 } else {
2131                     /* Constant address */
2132                     g_addaddr_static (flags, Expr->Name, Expr->Val);
2133                 }
2134             } else {
2135                 /* OOPS */
2136                 Error ("Invalid operands for binary operator `+'");
2137             }
2138
2139             /* Result is a rvalue in primary register */
2140             ED_MakeRValExpr (Expr);
2141         }
2142
2143     } else {
2144
2145         /* Left hand side is not constant. Get the value onto the stack. */
2146         ExprLoad (CF_NONE, Expr);              /* --> primary register */
2147         Mark = GetCodePos ();
2148         g_push (TypeOf (Expr->Type), 0);        /* --> stack */
2149
2150         /* Evaluate the rhs */
2151         if (evalexpr (CF_NONE, hie9, &Expr2) == 0) {
2152
2153             /* Right hand side is a constant. Get the rhs type */
2154             rhst = Expr2.Type;
2155
2156             /* Remove pushed value from stack */
2157             RemoveCode (Mark);
2158             pop (TypeOf (Expr->Type));
2159
2160             /* Check for pointer arithmetic */
2161             if (IsClassPtr (lhst) && IsClassInt (rhst)) {
2162                 /* Left is pointer, right is int, must scale rhs */
2163                 Expr2.Val *= CheckedPSizeOf (lhst);
2164                 /* Operate on pointers, result type is a pointer */
2165                 flags = CF_PTR;
2166             } else if (IsClassInt (lhst) && IsClassPtr (rhst)) {
2167                 /* Left is int, right is pointer, must scale lhs (ptr only) */
2168                 g_scale (CF_INT | CF_CONST, CheckedPSizeOf (rhst));
2169                 /* Operate on pointers, result type is a pointer */
2170                 flags = CF_PTR;
2171                 Expr->Type = Expr2.Type;
2172             } else if (IsClassInt (lhst) && IsClassInt (rhst)) {
2173                 /* Integer addition */
2174                 flags = typeadjust (Expr, &Expr2, 1);
2175             } else {
2176                 /* OOPS */
2177                 Error ("Invalid operands for binary operator `+'");
2178             }
2179
2180             /* Generate code for the add */
2181             g_inc (flags | CF_CONST, Expr2.Val);
2182
2183         } else {
2184
2185             /* lhs and rhs are not constant. Get the rhs type. */
2186             rhst = Expr2.Type;
2187
2188             /* Check for pointer arithmetic */
2189             if (IsClassPtr (lhst) && IsClassInt (rhst)) {
2190                 /* Left is pointer, right is int, must scale rhs */
2191                 g_scale (CF_INT, CheckedPSizeOf (lhst));
2192                 /* Operate on pointers, result type is a pointer */
2193                 flags = CF_PTR;
2194             } else if (IsClassInt (lhst) && IsClassPtr (rhst)) {
2195                 /* Left is int, right is pointer, must scale lhs */
2196                 g_tosint (TypeOf (rhst));       /* Make sure, TOS is int */
2197                 g_swap (CF_INT);                /* Swap TOS and primary */
2198                 g_scale (CF_INT, CheckedPSizeOf (rhst));
2199                 /* Operate on pointers, result type is a pointer */
2200                 flags = CF_PTR;
2201                 Expr->Type = Expr2.Type;
2202             } else if (IsClassInt (lhst) && IsClassInt (rhst)) {
2203                 /* Integer addition. Note: Result is never constant.
2204                  * Problem here is that typeadjust does not know if the
2205                  * variable is an rvalue or lvalue, so if both operands
2206                  * are dereferenced constant numeric addresses, typeadjust
2207                  * thinks the operation works on constants. Removing
2208                  * CF_CONST here means handling the symptoms, however, the
2209                  * whole parser is such a mess that I fear to break anything
2210                  * when trying to apply another solution.
2211                  */
2212                 flags = typeadjust (Expr, &Expr2, 0) & ~CF_CONST;
2213             } else {
2214                 /* OOPS */
2215                 Error ("Invalid operands for binary operator `+'");
2216             }
2217
2218             /* Generate code for the add */
2219             g_add (flags, 0);
2220
2221         }
2222
2223         /* Result is a rvalue in primary register */
2224         ED_MakeRValExpr (Expr);
2225     }
2226
2227     /* Condition codes not set */
2228     Expr->Test &= ~E_CC;
2229
2230 }
2231
2232
2233
2234 static void parsesub (ExprDesc* Expr)
2235 /* Parse an expression with the binary minus operator. Expr contains the
2236  * unprocessed left hand side of the expression and will contain the
2237  * result of the expression on return.
2238  */
2239 {
2240     ExprDesc Expr2;
2241     unsigned flags;             /* Operation flags */
2242     type* lhst;                 /* Type of left hand side */
2243     type* rhst;                 /* Type of right hand side */
2244     CodeMark Mark1;             /* Save position of output queue */
2245     CodeMark Mark2;             /* Another position in the queue */
2246     int rscale;                 /* Scale factor for the result */
2247
2248
2249     /* Skip the MINUS token */
2250     NextToken ();
2251
2252     /* Get the left hand side type, initialize operation flags */
2253     lhst = Expr->Type;
2254     flags = 0;
2255     rscale = 1;                 /* Scale by 1, that is, don't scale */
2256
2257     /* Remember the output queue position, then bring the value onto the stack */
2258     Mark1 = GetCodePos ();
2259     ExprLoad (CF_NONE, Expr);  /* --> primary register */
2260     Mark2 = GetCodePos ();
2261     g_push (TypeOf (lhst), 0);  /* --> stack */
2262
2263     /* Parse the right hand side */
2264     if (evalexpr (CF_NONE, hie9, &Expr2) == 0) {
2265
2266         /* The right hand side is constant. Get the rhs type. */
2267         rhst = Expr2.Type;
2268
2269         /* Check left hand side */
2270         if (ED_IsConstAbs (Expr)) {
2271
2272             /* Both sides are constant, remove generated code */
2273             RemoveCode (Mark1);
2274             pop (TypeOf (lhst));        /* Clean up the stack */
2275
2276             /* Check for pointer arithmetic */
2277             if (IsClassPtr (lhst) && IsClassInt (rhst)) {
2278                 /* Left is pointer, right is int, must scale rhs */
2279                 Expr->Val -= Expr2.Val * CheckedPSizeOf (lhst);
2280                 /* Operate on pointers, result type is a pointer */
2281             } else if (IsClassPtr (lhst) && IsClassPtr (rhst)) {
2282                 /* Left is pointer, right is pointer, must scale result */
2283                 if (TypeCmp (Indirect (lhst), Indirect (rhst)) < TC_QUAL_DIFF) {
2284                     Error ("Incompatible pointer types");
2285                 } else {
2286                     Expr->Val = (Expr->Val - Expr2.Val) /
2287                                       CheckedPSizeOf (lhst);
2288                 }
2289                 /* Operate on pointers, result type is an integer */
2290                 Expr->Type = type_int;
2291             } else if (IsClassInt (lhst) && IsClassInt (rhst)) {
2292                 /* Integer subtraction */
2293                 typeadjust (Expr, &Expr2, 1);
2294                 Expr->Val -= Expr2.Val;
2295             } else {
2296                 /* OOPS */
2297                 Error ("Invalid operands for binary operator `-'");
2298             }
2299
2300             /* Result is constant, condition codes not set */
2301             Expr->Test &= ~E_CC;
2302
2303         } else {
2304
2305             /* Left hand side is not constant, right hand side is.
2306              * Remove pushed value from stack.
2307              */
2308             RemoveCode (Mark2);
2309             pop (TypeOf (lhst));
2310
2311             if (IsClassPtr (lhst) && IsClassInt (rhst)) {
2312                 /* Left is pointer, right is int, must scale rhs */
2313                 Expr2.Val *= CheckedPSizeOf (lhst);
2314                 /* Operate on pointers, result type is a pointer */
2315                 flags = CF_PTR;
2316             } else if (IsClassPtr (lhst) && IsClassPtr (rhst)) {
2317                 /* Left is pointer, right is pointer, must scale result */
2318                 if (TypeCmp (Indirect (lhst), Indirect (rhst)) < TC_QUAL_DIFF) {
2319                     Error ("Incompatible pointer types");
2320                 } else {
2321                     rscale = CheckedPSizeOf (lhst);
2322                 }
2323                 /* Operate on pointers, result type is an integer */
2324                 flags = CF_PTR;
2325                 Expr->Type = type_int;
2326             } else if (IsClassInt (lhst) && IsClassInt (rhst)) {
2327                 /* Integer subtraction */
2328                 flags = typeadjust (Expr, &Expr2, 1);
2329             } else {
2330                 /* OOPS */
2331                 Error ("Invalid operands for binary operator `-'");
2332             }
2333
2334             /* Do the subtraction */
2335             g_dec (flags | CF_CONST, Expr2.Val);
2336
2337             /* If this was a pointer subtraction, we must scale the result */
2338             if (rscale != 1) {
2339                 g_scale (flags, -rscale);
2340             }
2341
2342             /* Result is a rvalue in the primary register */
2343             ED_MakeRValExpr (Expr);
2344             Expr->Test &= ~E_CC;
2345
2346         }
2347
2348     } else {
2349
2350         /* Right hand side is not constant. Get the rhs type. */
2351         rhst = Expr2.Type;
2352
2353         /* Check for pointer arithmetic */
2354         if (IsClassPtr (lhst) && IsClassInt (rhst)) {
2355             /* Left is pointer, right is int, must scale rhs */
2356             g_scale (CF_INT, CheckedPSizeOf (lhst));
2357             /* Operate on pointers, result type is a pointer */
2358             flags = CF_PTR;
2359         } else if (IsClassPtr (lhst) && IsClassPtr (rhst)) {
2360             /* Left is pointer, right is pointer, must scale result */
2361             if (TypeCmp (Indirect (lhst), Indirect (rhst)) < TC_QUAL_DIFF) {
2362                 Error ("Incompatible pointer types");
2363             } else {
2364                 rscale = CheckedPSizeOf (lhst);
2365             }
2366             /* Operate on pointers, result type is an integer */
2367             flags = CF_PTR;
2368             Expr->Type = type_int;
2369         } else if (IsClassInt (lhst) && IsClassInt (rhst)) {
2370             /* Integer subtraction. If the left hand side descriptor says that
2371              * the lhs is const, we have to remove this mark, since this is no
2372              * longer true, lhs is on stack instead.
2373              */
2374             if (ED_IsLocAbs (Expr)) {
2375                 ED_MakeRValExpr (Expr);
2376             }
2377             /* Adjust operand types */
2378             flags = typeadjust (Expr, &Expr2, 0);
2379         } else {
2380             /* OOPS */
2381             Error ("Invalid operands for binary operator `-'");
2382         }
2383
2384         /* Generate code for the sub (the & is a hack here) */
2385         g_sub (flags & ~CF_CONST, 0);
2386
2387         /* If this was a pointer subtraction, we must scale the result */
2388         if (rscale != 1) {
2389             g_scale (flags, -rscale);
2390         }
2391
2392         /* Result is a rvalue in the primary register */
2393         ED_MakeRValExpr (Expr);
2394         Expr->Test &= ~E_CC;
2395     }
2396 }
2397
2398
2399
2400 static void hie8 (ExprDesc* Expr)
2401 /* Process + and - binary operators. */
2402 {
2403     hie9 (Expr);
2404     while (CurTok.Tok == TOK_PLUS || CurTok.Tok == TOK_MINUS) {
2405         if (CurTok.Tok == TOK_PLUS) {
2406             parseadd (Expr);
2407         } else {
2408             parsesub (Expr);
2409         }
2410     }
2411 }
2412
2413
2414
2415 static void hie7 (ExprDesc* Expr)
2416 /* Parse << and >>. */
2417 {
2418     static const GenDesc hie7_ops [] = {
2419         { TOK_SHL,      GEN_NOPUSH,     g_asl   },
2420         { TOK_SHR,      GEN_NOPUSH,     g_asr   },
2421         { TOK_INVALID,  0,              0       }
2422     };
2423     int UsedGen;
2424
2425     hie_internal (hie7_ops, Expr, hie8, &UsedGen);
2426 }
2427
2428
2429
2430 static void hie6 (ExprDesc* Expr)
2431 /* Handle greater-than type comparators */
2432 {
2433     static const GenDesc hie6_ops [] = {
2434         { TOK_LT,       GEN_NOPUSH,     g_lt    },
2435         { TOK_LE,       GEN_NOPUSH,     g_le    },
2436         { TOK_GE,       GEN_NOPUSH,     g_ge    },
2437         { TOK_GT,       GEN_NOPUSH,     g_gt    },
2438         { TOK_INVALID,  0,              0       }
2439     };
2440     hie_compare (hie6_ops, Expr, hie7);
2441 }
2442
2443
2444
2445 static void hie5 (ExprDesc* Expr)
2446 /* Handle == and != */
2447 {
2448     static const GenDesc hie5_ops[] = {
2449         { TOK_EQ,       GEN_NOPUSH,     g_eq    },
2450         { TOK_NE,       GEN_NOPUSH,     g_ne    },
2451         { TOK_INVALID,  0,              0       }
2452     };
2453     hie_compare (hie5_ops, Expr, hie6);
2454 }
2455
2456
2457
2458 static void hie4 (ExprDesc* Expr)
2459 /* Handle & (bitwise and) */
2460 {
2461     static const GenDesc hie4_ops[] = {
2462         { TOK_AND,      GEN_NOPUSH,     g_and   },
2463         { TOK_INVALID,  0,              0       }
2464     };
2465     int UsedGen;
2466
2467     hie_internal (hie4_ops, Expr, hie5, &UsedGen);
2468 }
2469
2470
2471
2472 static void hie3 (ExprDesc* Expr)
2473 /* Handle ^ (bitwise exclusive or) */
2474 {
2475     static const GenDesc hie3_ops[] = {
2476         { TOK_XOR,      GEN_NOPUSH,     g_xor   },
2477         { TOK_INVALID,  0,              0       }
2478     };
2479     int UsedGen;
2480
2481     hie_internal (hie3_ops, Expr, hie4, &UsedGen);
2482 }
2483
2484
2485
2486 static void hie2 (ExprDesc* Expr)
2487 /* Handle | (bitwise or) */
2488 {
2489     static const GenDesc hie2_ops[] = {
2490         { TOK_OR,       GEN_NOPUSH,     g_or    },
2491         { TOK_INVALID,  0,              0       }
2492     };
2493     int UsedGen;
2494
2495     hie_internal (hie2_ops, Expr, hie3, &UsedGen);
2496 }
2497
2498
2499
2500 static void hieAndPP (ExprDesc* Expr)
2501 /* Process "exp && exp" in preprocessor mode (that is, when the parser is
2502  * called recursively from the preprocessor.
2503  */
2504 {
2505     ExprDesc Expr2;
2506
2507     ConstAbsIntExpr (hie2, Expr);
2508     while (CurTok.Tok == TOK_BOOL_AND) {
2509
2510         /* Skip the && */
2511         NextToken ();
2512
2513         /* Get rhs */
2514         ConstAbsIntExpr (hie2, &Expr2);
2515
2516         /* Combine the two */
2517         Expr->Val = (Expr->Val && Expr2.Val);
2518     }
2519 }
2520
2521
2522
2523 static void hieOrPP (ExprDesc *Expr)
2524 /* Process "exp || exp" in preprocessor mode (that is, when the parser is
2525  * called recursively from the preprocessor.
2526  */
2527 {
2528     ExprDesc Expr2;
2529
2530     ConstAbsIntExpr (hieAndPP, Expr);
2531     while (CurTok.Tok == TOK_BOOL_OR) {
2532
2533         /* Skip the && */
2534         NextToken ();
2535
2536         /* Get rhs */
2537         ConstAbsIntExpr (hieAndPP, &Expr2);
2538
2539         /* Combine the two */
2540         Expr->Val = (Expr->Val || Expr2.Val);
2541     }
2542 }
2543
2544
2545
2546 static void hieAnd (ExprDesc* Expr, unsigned TrueLab, int* BoolOp)
2547 /* Process "exp && exp" */
2548 {
2549     int lab;
2550     ExprDesc Expr2;
2551
2552     hie2 (Expr);
2553     if (CurTok.Tok == TOK_BOOL_AND) {
2554
2555         /* Tell our caller that we're evaluating a boolean */
2556         *BoolOp = 1;
2557
2558         /* Get a label that we will use for false expressions */
2559         lab = GetLocalLabel ();
2560
2561         /* If the expr hasn't set condition codes, set the force-test flag */
2562         if ((Expr->Test & E_CC) == 0) {
2563             Expr->Test |= E_FORCETEST;
2564         }
2565
2566         /* Load the value */
2567         ExprLoad (CF_FORCECHAR, Expr);
2568
2569         /* Generate the jump */
2570         g_falsejump (CF_NONE, lab);
2571
2572         /* Parse more boolean and's */
2573         while (CurTok.Tok == TOK_BOOL_AND) {
2574
2575             /* Skip the && */
2576             NextToken ();
2577
2578             /* Get rhs */
2579             hie2 (&Expr2);
2580             if ((Expr2.Test & E_CC) == 0) {
2581                 Expr2.Test |= E_FORCETEST;
2582             }
2583             ExprLoad (CF_FORCECHAR, &Expr2);
2584
2585             /* Do short circuit evaluation */
2586             if (CurTok.Tok == TOK_BOOL_AND) {
2587                 g_falsejump (CF_NONE, lab);
2588             } else {
2589                 /* Last expression - will evaluate to true */
2590                 g_truejump (CF_NONE, TrueLab);
2591             }
2592         }
2593
2594         /* Define the false jump label here */
2595         g_defcodelabel (lab);
2596
2597         /* The result is an rvalue in primary */
2598         ED_MakeRValExpr (Expr);
2599         Expr->Test |= E_CC;     /* Condition codes are set */
2600     }
2601 }
2602
2603
2604
2605 static void hieOr (ExprDesc *Expr)
2606 /* Process "exp || exp". */
2607 {
2608     ExprDesc Expr2;
2609     int BoolOp = 0;             /* Did we have a boolean op? */
2610     int AndOp;                  /* Did we have a && operation? */
2611     unsigned TrueLab;           /* Jump to this label if true */
2612     unsigned DoneLab;
2613
2614     /* Get a label */
2615     TrueLab = GetLocalLabel ();
2616
2617     /* Call the next level parser */
2618     hieAnd (Expr, TrueLab, &BoolOp);
2619
2620     /* Any boolean or's? */
2621     if (CurTok.Tok == TOK_BOOL_OR) {
2622
2623         /* If the expr hasn't set condition codes, set the force-test flag */
2624         if ((Expr->Test & E_CC) == 0) {
2625             Expr->Test |= E_FORCETEST;
2626         }
2627
2628         /* Get first expr */
2629         ExprLoad (CF_FORCECHAR, Expr);
2630
2631         /* For each expression jump to TrueLab if true. Beware: If we
2632          * had && operators, the jump is already in place!
2633          */
2634         if (!BoolOp) {
2635             g_truejump (CF_NONE, TrueLab);
2636         }
2637
2638         /* Remember that we had a boolean op */
2639         BoolOp = 1;
2640
2641         /* while there's more expr */
2642         while (CurTok.Tok == TOK_BOOL_OR) {
2643
2644             /* skip the || */
2645             NextToken ();
2646
2647             /* Get a subexpr */
2648             AndOp = 0;
2649             hieAnd (&Expr2, TrueLab, &AndOp);
2650             if ((Expr2.Test & E_CC) == 0) {
2651                 Expr2.Test |= E_FORCETEST;
2652             }
2653             ExprLoad (CF_FORCECHAR, &Expr2);
2654
2655             /* If there is more to come, add shortcut boolean eval. */
2656             g_truejump (CF_NONE, TrueLab);
2657
2658         }
2659
2660         /* The result is an rvalue in primary */
2661         ED_MakeRValExpr (Expr);
2662         Expr->Test |= E_CC;                     /* Condition codes are set */
2663     }
2664
2665     /* If we really had boolean ops, generate the end sequence */
2666     if (BoolOp) {
2667         DoneLab = GetLocalLabel ();
2668         g_getimmed (CF_INT | CF_CONST, 0, 0);   /* Load FALSE */
2669         g_falsejump (CF_NONE, DoneLab);
2670         g_defcodelabel (TrueLab);
2671         g_getimmed (CF_INT | CF_CONST, 1, 0);   /* Load TRUE */
2672         g_defcodelabel (DoneLab);
2673     }
2674 }
2675
2676
2677
2678 static void hieQuest (ExprDesc* Expr)
2679 /* Parse the ternary operator */
2680 {
2681     int         labf;
2682     int         labt;
2683     ExprDesc    Expr2;          /* Expression 2 */
2684     ExprDesc    Expr3;          /* Expression 3 */
2685     int         Expr2IsNULL;    /* Expression 2 is a NULL pointer */
2686     int         Expr3IsNULL;    /* Expression 3 is a NULL pointer */
2687     type*       ResultType;     /* Type of result */
2688
2689
2690     /* Call the lower level eval routine */
2691     if (Preprocessing) {
2692         hieOrPP (Expr);
2693     } else {
2694         hieOr (Expr);
2695     }
2696
2697     /* Check if it's a ternary expression */
2698     if (CurTok.Tok == TOK_QUEST) {
2699         NextToken ();
2700         if ((Expr->Test & E_CC) == 0) {
2701             /* Condition codes not set, force a test */
2702             Expr->Test |= E_FORCETEST;
2703         }
2704         ExprLoad (CF_NONE, Expr);
2705         labf = GetLocalLabel ();
2706         g_falsejump (CF_NONE, labf);
2707
2708         /* Parse second expression. Remember for later if it is a NULL pointer
2709          * expression, then load it into the primary.
2710          */
2711         ExprWithCheck (hie1, &Expr2);
2712         Expr2IsNULL = ED_IsNullPtr (&Expr2);
2713         if (!IsTypeVoid (Expr2.Type)) {
2714             /* Load it into the primary */
2715             ExprLoad (CF_NONE, &Expr2);
2716             ED_MakeRValExpr (&Expr2);
2717         }
2718         labt = GetLocalLabel ();
2719         ConsumeColon ();
2720         g_jump (labt);
2721
2722         /* Jump here if the first expression was false */
2723         g_defcodelabel (labf);
2724
2725         /* Parse second expression. Remember for later if it is a NULL pointer
2726          * expression, then load it into the primary.
2727          */
2728         ExprWithCheck (hie1, &Expr3);
2729         Expr3IsNULL = ED_IsNullPtr (&Expr3);
2730         if (!IsTypeVoid (Expr3.Type)) {
2731             /* Load it into the primary */
2732             ExprLoad (CF_NONE, &Expr3);
2733             ED_MakeRValExpr (&Expr3);
2734         }
2735
2736         /* Check if any conversions are needed, if so, do them.
2737          * Conversion rules for ?: expression are:
2738          *   - if both expressions are int expressions, default promotion
2739          *     rules for ints apply.
2740          *   - if both expressions are pointers of the same type, the
2741          *     result of the expression is of this type.
2742          *   - if one of the expressions is a pointer and the other is
2743          *     a zero constant, the resulting type is that of the pointer
2744          *     type.
2745          *   - if both expressions are void expressions, the result is of
2746          *     type void.
2747          *   - all other cases are flagged by an error.
2748          */
2749         if (IsClassInt (Expr2.Type) && IsClassInt (Expr3.Type)) {
2750
2751             /* Get common type */
2752             ResultType = promoteint (Expr2.Type, Expr3.Type);
2753
2754             /* Convert the third expression to this type if needed */
2755             TypeConversion (&Expr3, ResultType);
2756
2757             /* Setup a new label so that the expr3 code will jump around
2758              * the type cast code for expr2.
2759              */
2760             labf = GetLocalLabel ();    /* Get new label */
2761             g_jump (labf);              /* Jump around code */
2762
2763             /* The jump for expr2 goes here */
2764             g_defcodelabel (labt);
2765
2766             /* Create the typecast code for expr2 */
2767             TypeConversion (&Expr2, ResultType);
2768
2769             /* Jump here around the typecase code. */
2770             g_defcodelabel (labf);
2771             labt = 0;           /* Mark other label as invalid */
2772
2773         } else if (IsClassPtr (Expr2.Type) && IsClassPtr (Expr3.Type)) {
2774             /* Must point to same type */
2775             if (TypeCmp (Indirect (Expr2.Type), Indirect (Expr3.Type)) < TC_EQUAL) {
2776                 Error ("Incompatible pointer types");
2777             }
2778             /* Result has the common type */
2779             ResultType = Expr2.Type;
2780         } else if (IsClassPtr (Expr2.Type) && Expr3IsNULL) {
2781             /* Result type is pointer, no cast needed */
2782             ResultType = Expr2.Type;
2783         } else if (Expr2IsNULL && IsClassPtr (Expr3.Type)) {
2784             /* Result type is pointer, no cast needed */
2785             ResultType = Expr3.Type;
2786         } else if (IsTypeVoid (Expr2.Type) && IsTypeVoid (Expr3.Type)) {
2787             /* Result type is void */
2788             ResultType = Expr3.Type;
2789         } else {
2790             Error ("Incompatible types");
2791             ResultType = Expr2.Type;            /* Doesn't matter here */
2792         }
2793
2794         /* If we don't have the label defined until now, do it */
2795         if (labt) {
2796             g_defcodelabel (labt);
2797         }
2798
2799         /* Setup the target expression */
2800         ED_MakeRValExpr (Expr);
2801         Expr->Type  = ResultType;
2802     }
2803 }
2804
2805
2806
2807 static void opeq (const GenDesc* Gen, ExprDesc* Expr)
2808 /* Process "op=" operators. */
2809 {
2810     ExprDesc Expr2;
2811     unsigned flags;
2812     CodeMark Mark;
2813     int MustScale;
2814
2815     /* op= can only be used with lvalues */
2816     if (!ED_IsLVal (Expr)) {
2817         Error ("Invalid lvalue in assignment");
2818         return;
2819     }
2820
2821     /* There must be an integer or pointer on the left side */
2822     if (!IsClassInt (Expr->Type) && !IsTypePtr (Expr->Type)) {
2823         Error ("Invalid left operand type");
2824         /* Continue. Wrong code will be generated, but the compiler won't
2825          * break, so this is the best error recovery.
2826          */
2827     }
2828
2829     /* Skip the operator token */
2830     NextToken ();
2831
2832     /* Determine the type of the lhs */
2833     flags = TypeOf (Expr->Type);
2834     MustScale = (Gen->Func == g_add || Gen->Func == g_sub) && IsTypePtr (Expr->Type);
2835
2836     /* Get the lhs address on stack (if needed) */
2837     PushAddr (Expr);
2838
2839     /* Fetch the lhs into the primary register if needed */
2840     ExprLoad (CF_NONE, Expr);
2841
2842     /* Bring the lhs on stack */
2843     Mark = GetCodePos ();
2844     g_push (flags, 0);
2845
2846     /* Evaluate the rhs */
2847     if (evalexpr (CF_NONE, hie1, &Expr2) == 0) {
2848         /* The resulting value is a constant. If the generator has the NOPUSH
2849          * flag set, don't push the lhs.
2850          */
2851         if (Gen->Flags & GEN_NOPUSH) {
2852             RemoveCode (Mark);
2853             pop (flags);
2854         }
2855         if (MustScale) {
2856             /* lhs is a pointer, scale rhs */
2857             Expr2.Val *= CheckedSizeOf (Expr->Type+1);
2858         }
2859
2860         /* If the lhs is character sized, the operation may be later done
2861          * with characters.
2862          */
2863         if (CheckedSizeOf (Expr->Type) == SIZEOF_CHAR) {
2864             flags |= CF_FORCECHAR;
2865         }
2866
2867         /* Special handling for add and sub - some sort of a hack, but short code */
2868         if (Gen->Func == g_add) {
2869             g_inc (flags | CF_CONST, Expr2.Val);
2870         } else if (Gen->Func == g_sub) {
2871             g_dec (flags | CF_CONST, Expr2.Val);
2872         } else {
2873             Gen->Func (flags | CF_CONST, Expr2.Val);
2874         }
2875     } else {
2876         /* rhs is not constant and already in the primary register */
2877         if (MustScale) {
2878             /* lhs is a pointer, scale rhs */
2879             g_scale (TypeOf (Expr2.Type), CheckedSizeOf (Expr->Type+1));
2880         }
2881
2882         /* If the lhs is character sized, the operation may be later done
2883          * with characters.
2884          */
2885         if (CheckedSizeOf (Expr->Type) == SIZEOF_CHAR) {
2886             flags |= CF_FORCECHAR;
2887         }
2888
2889         /* Adjust the types of the operands if needed */
2890         Gen->Func (g_typeadjust (flags, TypeOf (Expr2.Type)), 0);
2891     }
2892     Store (Expr, 0);
2893     ED_MakeRValExpr (Expr);
2894 }
2895
2896
2897
2898 static void addsubeq (const GenDesc* Gen, ExprDesc *Expr)
2899 /* Process the += and -= operators */
2900 {
2901     ExprDesc Expr2;
2902     unsigned lflags;
2903     unsigned rflags;
2904     int      MustScale;
2905
2906
2907     /* We're currently only able to handle some adressing modes */
2908     if (ED_GetLoc (Expr) == E_LOC_EXPR || ED_GetLoc (Expr) == E_LOC_PRIMARY) {
2909         /* Use generic routine */
2910         opeq (Gen, Expr);
2911         return;
2912     }
2913
2914     /* We must have an lvalue */
2915     if (ED_IsRVal (Expr)) {
2916         Error ("Invalid lvalue in assignment");
2917         return;
2918     }
2919
2920     /* There must be an integer or pointer on the left side */
2921     if (!IsClassInt (Expr->Type) && !IsTypePtr (Expr->Type)) {
2922         Error ("Invalid left operand type");
2923         /* Continue. Wrong code will be generated, but the compiler won't
2924          * break, so this is the best error recovery.
2925          */
2926     }
2927
2928     /* Skip the operator */
2929     NextToken ();
2930
2931     /* Check if we have a pointer expression and must scale rhs */
2932     MustScale = IsTypePtr (Expr->Type);
2933
2934     /* Initialize the code generator flags */
2935     lflags = 0;
2936     rflags = 0;
2937
2938     /* Evaluate the rhs */
2939     hie1 (&Expr2);
2940     if (ED_IsConstAbs (&Expr2)) {
2941         /* The resulting value is a constant. Scale it. */
2942         if (MustScale) {
2943             Expr2.Val *= CheckedSizeOf (Indirect (Expr->Type));
2944         }
2945         rflags |= CF_CONST;
2946         lflags |= CF_CONST;
2947     } else {
2948         /* Not constant, load into the primary */
2949         ExprLoad (CF_NONE, &Expr2);
2950         if (MustScale) {
2951             /* lhs is a pointer, scale rhs */
2952             g_scale (TypeOf (Expr2.Type), CheckedSizeOf (Indirect (Expr->Type)));
2953         }
2954     }
2955
2956     /* Setup the code generator flags */
2957     lflags |= TypeOf (Expr->Type) | CF_FORCECHAR;
2958     rflags |= TypeOf (Expr2.Type);
2959
2960     /* Convert the type of the lhs to that of the rhs */
2961     g_typecast (lflags, rflags);
2962
2963     /* Output apropriate code depending on the location */
2964     switch (ED_GetLoc (Expr)) {
2965
2966         case E_LOC_ABS:
2967             /* Absolute: numeric address or const */
2968             lflags |= CF_ABSOLUTE;
2969             if (Gen->Tok == TOK_PLUS_ASSIGN) {
2970                 g_addeqstatic (lflags, Expr->Name, Expr->Val, Expr2.Val);
2971             } else {
2972                 g_subeqstatic (lflags, Expr->Name, Expr->Val, Expr2.Val);
2973             }
2974             break;
2975
2976         case E_LOC_GLOBAL:
2977             /* Global variable */
2978             lflags |= CF_EXTERNAL;
2979             if (Gen->Tok == TOK_PLUS_ASSIGN) {
2980                 g_addeqstatic (lflags, Expr->Name, Expr->Val, Expr2.Val);
2981             } else {
2982                 g_subeqstatic (lflags, Expr->Name, Expr->Val, Expr2.Val);
2983             }
2984             break;
2985
2986         case E_LOC_STATIC:
2987         case E_LOC_LITERAL:
2988             /* Static variable or literal in the literal pool */
2989             lflags |= CF_STATIC;
2990             if (Gen->Tok == TOK_PLUS_ASSIGN) {
2991                 g_addeqstatic (lflags, Expr->Name, Expr->Val, Expr2.Val);
2992             } else {
2993                 g_subeqstatic (lflags, Expr->Name, Expr->Val, Expr2.Val);
2994             }
2995             break;
2996
2997         case E_LOC_REGISTER:
2998             /* Register variable */
2999             lflags |= CF_REGVAR;
3000             if (Gen->Tok == TOK_PLUS_ASSIGN) {
3001                 g_addeqstatic (lflags, Expr->Name, Expr->Val, Expr2.Val);
3002             } else {
3003                 g_subeqstatic (lflags, Expr->Name, Expr->Val, Expr2.Val);
3004             }
3005             break;
3006
3007         case E_LOC_STACK:
3008             /* Value on the stack */
3009             if (Gen->Tok == TOK_PLUS_ASSIGN) {
3010                 g_addeqlocal (lflags, Expr->Val, Expr2.Val);
3011             } else {
3012                 g_subeqlocal (lflags, Expr->Val, Expr2.Val);
3013             }
3014             break;
3015
3016         default:
3017             Internal ("Invalid location in Store(): 0x%04X", ED_GetLoc (Expr));
3018     }
3019
3020     /* Expression is a rvalue in the primary now */
3021     ED_MakeRValExpr (Expr);
3022 }
3023
3024
3025
3026 void hie1 (ExprDesc* Expr)
3027 /* Parse first level of expression hierarchy. */
3028 {
3029     hieQuest (Expr);
3030     switch (CurTok.Tok) {
3031
3032         case TOK_ASSIGN:
3033             Assignment (Expr);
3034             break;
3035
3036         case TOK_PLUS_ASSIGN:
3037             addsubeq (&GenPASGN, Expr);
3038             break;
3039
3040         case TOK_MINUS_ASSIGN:
3041             addsubeq (&GenSASGN, Expr);
3042             break;
3043
3044         case TOK_MUL_ASSIGN:
3045             opeq (&GenMASGN, Expr);
3046             break;
3047
3048         case TOK_DIV_ASSIGN:
3049             opeq (&GenDASGN, Expr);
3050             break;
3051
3052         case TOK_MOD_ASSIGN:
3053             opeq (&GenMOASGN, Expr);
3054             break;
3055
3056         case TOK_SHL_ASSIGN:
3057             opeq (&GenSLASGN, Expr);
3058             break;
3059
3060         case TOK_SHR_ASSIGN:
3061             opeq (&GenSRASGN, Expr);
3062             break;
3063
3064         case TOK_AND_ASSIGN:
3065             opeq (&GenAASGN, Expr);
3066             break;
3067
3068         case TOK_XOR_ASSIGN:
3069             opeq (&GenXOASGN, Expr);
3070             break;
3071
3072         case TOK_OR_ASSIGN:
3073             opeq (&GenOASGN, Expr);
3074             break;
3075
3076         default:
3077             break;
3078     }
3079 }
3080
3081
3082
3083 void hie0 (ExprDesc *Expr)
3084 /* Parse comma operator. */
3085 {
3086     hie1 (Expr);
3087     while (CurTok.Tok == TOK_COMMA) {
3088         NextToken ();
3089         hie1 (Expr);
3090     }
3091 }
3092
3093
3094
3095 int evalexpr (unsigned Flags, void (*Func) (ExprDesc*), ExprDesc* Expr)
3096 /* Will evaluate an expression via the given function. If the result is a
3097  * constant, 0 is returned and the value is put in the Expr struct. If the
3098  * result is not constant, ExprLoad is called to bring the value into the
3099  * primary register and 1 is returned.
3100  */
3101 {
3102     /* Evaluate */
3103     ExprWithCheck (Func, Expr);
3104
3105     /* Check for a constant expression */
3106     if (ED_IsConstAbs (Expr)) {
3107         /* Constant expression */
3108         return 0;
3109     } else {
3110         /* Not constant, load into the primary */
3111         ExprLoad (Flags, Expr);
3112         return 1;
3113     }
3114 }
3115
3116
3117
3118 void Expression0 (ExprDesc* Expr)
3119 /* Evaluate an expression via hie0 and put the result into the primary register */
3120 {
3121     ExprWithCheck (hie0, Expr);
3122     ExprLoad (CF_NONE, Expr);
3123 }
3124
3125
3126
3127 void ConstExpr (void (*Func) (ExprDesc*), ExprDesc* Expr)
3128 /* Will evaluate an expression via the given function. If the result is not
3129  * a constant of some sort, a diagnostic will be printed, and the value is
3130  * replaced by a constant one to make sure there are no internal errors that
3131  * result from this input error.
3132  */
3133 {
3134     ExprWithCheck (Func, Expr);
3135     if (!ED_IsConst (Expr)) {
3136         Error ("Constant expression expected");
3137         /* To avoid any compiler errors, make the expression a valid const */
3138         ED_MakeConstAbsInt (Expr, 1);
3139     }
3140 }
3141
3142
3143
3144 void BoolExpr (void (*Func) (ExprDesc*), ExprDesc* Expr)
3145 /* Will evaluate an expression via the given function. If the result is not
3146  * something that may be evaluated in a boolean context, a diagnostic will be
3147  * printed, and the value is replaced by a constant one to make sure there
3148  * are no internal errors that result from this input error.
3149  */
3150 {
3151     ExprWithCheck (Func, Expr);
3152     if (!ED_IsBool (Expr)) {
3153         Error ("Boolean expression expected");
3154         /* To avoid any compiler errors, make the expression a valid int */
3155         ED_MakeConstAbsInt (Expr, 1);
3156     }
3157 }
3158
3159
3160
3161 void ConstAbsIntExpr (void (*Func) (ExprDesc*), ExprDesc* Expr)
3162 /* Will evaluate an expression via the given function. If the result is not
3163  * a constant numeric integer value, a diagnostic will be printed, and the
3164  * value is replaced by a constant one to make sure there are no internal
3165  * errors that result from this input error.
3166  */
3167 {
3168     ExprWithCheck (Func, Expr);
3169     if (!ED_IsConstAbsInt (Expr)) {
3170         Error ("Constant integer expression expected");
3171         /* To avoid any compiler errors, make the expression a valid const */
3172         ED_MakeConstAbsInt (Expr, 1);
3173     }
3174 }
3175
3176
3177