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