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