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