]> git.sur5r.net Git - cc65/blob - src/cc65/expr.c
f517933f4f11afd1aeb1c29e3e04c7e6ecbfa18e
[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, LiteralLabel, 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, LiteralLabel, 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     /* Return the size of all parameters pushed onto the stack */
678     return ParamSize;
679 }
680
681
682
683 static void CallFunction (struct expent* lval)
684 /* Perform a function call.  Called from hie11, this routine will
685  * either call the named function, or the function pointer in a/x.
686  */
687 {
688     FuncDesc*     Func;         /* Function descriptor */
689     unsigned      ParamSize;    /* Number of parameter bytes */
690     CodeMark      Mark;
691
692
693     /* Get a pointer to the function descriptor from the type string */
694     Func = GetFuncDesc (lval->e_tptr);
695
696     /* Initialize vars to keep gcc silent */
697     Mark  = 0;
698
699     /* Check if this is a function pointer. If so, save it. If not, check for
700      * special known library functions that may be inlined.
701      */
702     if (lval->e_flags & E_MEXPR) {
703         /* Function pointer is in primary register, save it */
704         Mark = GetCodePos ();
705         g_save (CF_PTR);
706     } else if (InlineStdFuncs && IsStdFunc ((const char*) lval->e_name)) {
707         /* Inline this function */
708         HandleStdFunc (lval);
709         return;
710     }
711
712     /* Parse the parameter list */
713     ParamSize = FunctionParamList (Func);
714
715     /* We need the closing bracket here */
716     ConsumeRParen ();
717
718     /* */
719     if (lval->e_flags & E_MEXPR) {
720         /* Function called via pointer: Restore it and call function */
721         if (ParamSize != 0) {
722             g_restore (CF_PTR);
723         } else {
724             /* We had no parameters - remove save code */
725             RemoveCode (Mark);
726         }
727         g_callind (TypeOf (lval->e_tptr), ParamSize);
728     } else {
729         g_call (TypeOf (lval->e_tptr), (const char*) lval->e_name, ParamSize);
730     }
731 }
732
733
734
735 void doasm (void)
736 /* This function parses ASM statements. The syntax of the ASM directive
737  * looks like the one defined for C++ (C has no ASM directive), that is,
738  * a string literal in parenthesis.
739  */
740 {
741     /* Skip the ASM */
742     NextToken ();
743
744     /* Need left parenthesis */
745     ConsumeLParen ();
746
747     /* String literal */
748     if (curtok != TOK_SCONST) {
749         Error ("String literal expected");
750     } else {
751         /* Write the string directly into the output, followed by a newline */
752         AddCodeLine (GetLiteral (curval));
753
754         /* Reset the string pointer, effectivly clearing the string from the
755          * string table. Since we're working with one token lookahead, this
756          * will fail if the next token is also a string token, but that's a
757          * syntax error anyway, because we expect a right paren.
758          */
759         ResetLiteralOffs (curval);
760     }
761
762     /* Skip the string token */
763     NextToken ();
764
765     /* Closing paren needed */
766     ConsumeRParen ();
767 }
768
769
770
771 static int primary (struct expent* lval)
772 /* This is the lowest level of the expression parser. */
773 {
774     int k;
775
776     /* not a test at all, yet */
777     lval->e_test = 0;
778
779     /* Character and integer constants. */
780     if (curtok == TOK_ICONST || curtok == TOK_CCONST) {
781         lval->e_flags = E_MCONST | E_TCONST;
782         lval->e_tptr  = curtype;
783         lval->e_const = curval;
784         NextToken ();
785         return 0;
786     }
787
788     /* Process parenthesized subexpression by calling the whole parser
789      * recursively.
790      */
791     if (curtok == TOK_LPAREN) {
792         NextToken ();
793         memset (lval, 0, sizeof (*lval));       /* Remove any attributes */
794         k = hie0 (lval);
795         ConsumeRParen ();
796         return k;
797     }
798
799     /* All others may only be used if the expression evaluation is not called
800      * recursively by the preprocessor.
801      */
802     if (Preprocessing) {
803         /* Illegal expression in PP mode */
804         Error ("Preprocessor expression expected");
805         lval->e_flags = E_MCONST;
806         lval->e_tptr = type_int;
807         return 0;
808     }
809
810     /* Identifier? */
811     if (curtok == TOK_IDENT) {
812
813         SymEntry* Sym;
814         ident Ident;
815
816         /* Get a pointer to the symbol table entry */
817         Sym = FindSym (CurTok.Ident);
818
819         /* Is the symbol known? */
820         if (Sym) {
821
822             /* We found the symbol - skip the name token */
823             NextToken ();
824
825             /* The expression type is the symbol type */
826             lval->e_tptr = Sym->Type;
827
828             /* Check for illegal symbol types */
829             CHECK ((Sym->Flags & SC_LABEL) != SC_LABEL);
830             if (Sym->Flags & SC_TYPE) {
831                 /* Cannot use type symbols */
832                 Error ("Variable identifier expected");
833                 /* Assume an int type to make lval valid */
834                 lval->e_flags = E_MLOCAL | E_TLOFFS;
835                 lval->e_tptr = type_int;
836                 lval->e_const = 0;
837                 return 0;
838             }
839
840             /* Check for legal symbol types */
841             if ((Sym->Flags & SC_CONST) == SC_CONST) {
842                 /* Enum or some other numeric constant */
843                 lval->e_flags = E_MCONST;
844                 lval->e_const = Sym->V.ConstVal;
845                 return 0;
846             } else if ((Sym->Flags & SC_FUNC) == SC_FUNC) {
847                 /* Function */
848                 lval->e_flags = E_MGLOBAL | E_MCONST | E_TGLAB;
849                 lval->e_name = (unsigned long) Sym->Name;
850                 lval->e_const = 0;
851             } else if ((Sym->Flags & SC_AUTO) == SC_AUTO) {
852                 /* Local variable. If this is a parameter for a variadic
853                  * function, we have to add some address calculations, and the
854                  * address is not const.
855                  */
856                 if ((Sym->Flags & SC_PARAM) == SC_PARAM && IsVariadic (CurrentFunc)) {
857                     /* Variadic parameter */
858                     g_leavariadic (Sym->V.Offs - GetParamSize (CurrentFunc));
859                     lval->e_flags = E_MEXPR;
860                     lval->e_const = 0;
861                 } else {
862                     /* Normal parameter */
863                     lval->e_flags = E_MLOCAL | E_TLOFFS;
864                     lval->e_const = Sym->V.Offs;
865                 }
866             } else if ((Sym->Flags & SC_STATIC) == SC_STATIC) {
867                 /* Static variable */
868                 if (Sym->Flags & (SC_EXTERN | SC_STORAGE)) {
869                     lval->e_flags = E_MGLOBAL | E_MCONST | E_TGLAB;
870                     lval->e_name = (unsigned long) Sym->Name;
871                 } else {
872                     lval->e_flags = E_MGLOBAL | E_MCONST | E_TLLAB;
873                     lval->e_name = Sym->V.Label;
874                 }
875                 lval->e_const = 0;
876             } else if ((Sym->Flags & SC_REGISTER) == SC_REGISTER) {
877                 /* Register variable, zero page based */
878                 lval->e_flags = E_MGLOBAL | E_MCONST | E_TREGISTER;
879                 lval->e_name  = Sym->V.Offs;
880                 lval->e_const = 0;
881             } else {
882                 /* Local static variable */
883                 lval->e_flags = E_MGLOBAL | E_MCONST | E_TLLAB;
884                 lval->e_name  = Sym->V.Offs;
885                 lval->e_const = 0;
886             }
887
888             /* The symbol is referenced now */
889             Sym->Flags |= SC_REF;
890             if (IsTypeFunc (lval->e_tptr) || IsTypeArray (lval->e_tptr)) {
891                 return 0;
892             }
893             return 1;
894         }
895
896         /* We did not find the symbol. Remember the name, then skip it */
897         strcpy (Ident, CurTok.Ident);
898         NextToken ();
899
900         /* IDENT is either an auto-declared function or an undefined variable. */
901         if (curtok == TOK_LPAREN) {
902             /* Declare a function returning int. For that purpose, prepare a
903              * function signature for a function having an empty param list
904              * and returning int.
905              */
906             Warning ("Function call without a prototype");
907             Sym = AddGlobalSym (Ident, GetImplicitFuncType(), SC_EXTERN | SC_REF | SC_FUNC);
908             lval->e_tptr  = Sym->Type;
909             lval->e_flags = E_MGLOBAL | E_MCONST | E_TGLAB;
910             lval->e_name  = (unsigned long) Sym->Name;
911             lval->e_const = 0;
912             return 0;
913
914         } else {
915
916             /* Undeclared Variable */
917             Sym = AddLocalSym (Ident, type_int, SC_AUTO | SC_REF, 0);
918             lval->e_flags = E_MLOCAL | E_TLOFFS;
919             lval->e_tptr = type_int;
920             lval->e_const = 0;
921             Error ("Undefined symbol: `%s'", Ident);
922             return 1;
923
924         }
925     }
926
927     /* String literal? */
928     if (curtok == TOK_SCONST) {
929         lval->e_flags = E_MCONST | E_TLIT;
930         lval->e_const = curval;
931         lval->e_tptr  = GetCharArrayType (strlen (GetLiteral (curval)));
932         NextToken ();
933         return 0;
934     }
935
936     /* ASM statement? */
937     if (curtok == TOK_ASM) {
938         doasm ();
939         lval->e_tptr  = type_void;
940         lval->e_flags = E_MEXPR;
941         lval->e_const = 0;
942         return 0;
943     }
944
945     /* __AX__ and __EAX__ pseudo values? */
946     if (curtok == TOK_AX || curtok == TOK_EAX) {
947         lval->e_tptr  = (curtok == TOK_AX)? type_uint : type_ulong;
948         lval->e_flags = E_MREG;
949         lval->e_test &= ~E_CC;
950         lval->e_const = 0;
951         NextToken ();
952         return 1;               /* May be used as lvalue */
953     }
954
955     /* Illegal primary. */
956     Error ("Expression expected");
957     lval->e_flags = E_MCONST;
958     lval->e_tptr = type_int;
959     return 0;
960 }
961
962
963
964 static int arrayref (int k, struct expent* lval)
965 /* Handle an array reference */
966 {
967     unsigned lflags;
968     unsigned rflags;
969     int ConstBaseAddr;
970     int ConstSubAddr;
971     int l;
972     struct expent lval2;
973     CodeMark Mark1;
974     CodeMark Mark2;
975     type* tptr1;
976     type* tptr2;
977
978
979     /* Skip the bracket */
980     NextToken ();
981
982     /* Get the type of left side */
983     tptr1 = lval->e_tptr;
984
985     /* We can apply a special treatment for arrays that have a const base
986      * address. This is true for most arrays and will produce a lot better
987      * code. Check if this is a const base address.
988      */
989     lflags = lval->e_flags & ~E_MCTYPE;
990     ConstBaseAddr = (lflags == E_MCONST)       || /* Constant numeric address */
991                      (lflags & E_MGLOBAL) != 0 || /* Static array, or ... */
992                      lflags == E_MLOCAL;          /* Local array */
993
994     /* If we have a constant base, we delay the address fetch */
995     Mark1 = GetCodePos ();
996     Mark2 = 0;          /* Silence gcc */
997     if (!ConstBaseAddr) {
998         /* Get a pointer to the array into the primary */
999         exprhs (CF_NONE, k, lval);
1000
1001         /* Get the array pointer on stack. Do not push more than 16
1002          * bit, even if this value is greater, since we cannot handle
1003          * other than 16bit stuff when doing indexing.
1004          */
1005         Mark2 = GetCodePos ();
1006         g_push (CF_PTR, 0);
1007     }
1008
1009     /* TOS now contains ptr to array elements. Get the subscript. */
1010     l = hie0 (&lval2);
1011     if (l == 0 && lval2.e_flags == E_MCONST) {
1012
1013         /* The array subscript is a constant - remove value from stack */
1014         if (!ConstBaseAddr) {
1015             RemoveCode (Mark2);
1016             pop (CF_PTR);
1017         } else {
1018             /* Get an array pointer into the primary */
1019             exprhs (CF_NONE, k, lval);
1020         }
1021
1022         if (IsClassPtr (tptr1)) {
1023
1024             /* Scale the subscript value according to element size */
1025             lval2.e_const *= PSizeOf (tptr1);
1026
1027             /* Remove code for lhs load */
1028             RemoveCode (Mark1);
1029
1030             /* Handle constant base array on stack. Be sure NOT to
1031              * handle pointers the same way, this won't work.
1032              */
1033             if (IsTypeArray (tptr1) &&
1034                 ((lval->e_flags & ~E_MCTYPE) == E_MCONST ||
1035                 (lval->e_flags & ~E_MCTYPE) == E_MLOCAL ||
1036                 (lval->e_flags & E_MGLOBAL) != 0 ||
1037                 (lval->e_flags == E_MEOFFS))) {
1038                 lval->e_const += lval2.e_const;
1039
1040             } else {
1041                 /* Pointer - load into primary and remember offset */
1042                 if ((lval->e_flags & E_MEXPR) == 0 || k != 0) {
1043                     exprhs (CF_NONE, k, lval);
1044                 }
1045                 lval->e_const = lval2.e_const;
1046                 lval->e_flags = E_MEOFFS;
1047             }
1048
1049             /* Result is of element type */
1050             lval->e_tptr = Indirect (tptr1);
1051
1052             /* Done */
1053             goto end_array;
1054
1055         } else if (IsClassPtr (tptr2 = lval2.e_tptr)) {
1056             /* Subscript is pointer, get element type */
1057             lval2.e_tptr = Indirect (tptr2);
1058
1059             /* Scale the rhs value in the primary register */
1060             g_scale (TypeOf (tptr1), SizeOf (lval2.e_tptr));
1061             /* */
1062             lval->e_tptr = lval2.e_tptr;
1063         } else {
1064             Error ("Cannot subscript");
1065         }
1066
1067         /* Add the subscript. Since arrays are indexed by integers,
1068          * we will ignore the true type of the subscript here and
1069          * use always an int.
1070          */
1071         g_inc (CF_INT | CF_CONST, lval2.e_const);
1072
1073     } else {
1074
1075         /* Array subscript is not constant. Load it into the primary */
1076         Mark2 = GetCodePos ();
1077         exprhs (CF_NONE, l, &lval2);
1078
1079         tptr2 = lval2.e_tptr;
1080         if (IsClassPtr (tptr1)) {
1081
1082             /* Get the element type */
1083             lval->e_tptr = Indirect (tptr1);
1084
1085             /* Indexing is based on int's, so we will just use the integer
1086              * portion of the index (which is in (e)ax, so there's no further
1087              * action required).
1088              */
1089             g_scale (CF_INT, SizeOf (lval->e_tptr));
1090
1091         } else if (IsClassPtr (tptr2)) {
1092
1093             /* Get the element type */
1094             lval2.e_tptr = Indirect (tptr2);
1095
1096             /* Get the int value on top. If we go here, we're sure,
1097              * both values are 16 bit (the first one was truncated
1098              * if necessary and the second one is a pointer).
1099              * Note: If ConstBaseAddr is true, we don't have a value on
1100              * stack, so to "swap" both, just push the subscript.
1101              */
1102             if (ConstBaseAddr) {
1103                 g_push (CF_INT, 0);
1104                 exprhs (CF_NONE, k, lval);
1105                 ConstBaseAddr = 0;
1106             } else {
1107                 g_swap (CF_INT);
1108             }
1109
1110             /* Scale it */
1111             g_scale (TypeOf (tptr1), SizeOf (lval2.e_tptr));
1112             lval->e_tptr = lval2.e_tptr;
1113         } else {
1114             Error ("Cannot subscript");
1115         }
1116
1117         /* The offset is now in the primary register. It didn't have a
1118          * constant base address for the lhs, the lhs address is already
1119          * on stack, and we must add the offset. If the base address was
1120          * constant, we call special functions to add the address to the
1121          * offset value.
1122          */
1123         if (!ConstBaseAddr) {
1124             /* Add the subscript. Both values are int sized. */
1125             g_add (CF_INT, 0);
1126         } else {
1127
1128             /* If the subscript has itself a constant address, it is often
1129              * a better idea to reverse again the order of the evaluation.
1130              * This will generate better code if the subscript is a byte
1131              * sized variable. But beware: This is only possible if the
1132              * subscript was not scaled, that is, if this was a byte array
1133              * or pointer.
1134              */
1135             rflags = lval2.e_flags & ~E_MCTYPE;
1136             ConstSubAddr = (rflags == E_MCONST)       || /* Constant numeric address */
1137                             (rflags & E_MGLOBAL) != 0 || /* Static array, or ... */
1138                             rflags == E_MLOCAL;          /* Local array */
1139
1140             if (ConstSubAddr && SizeOf (lval->e_tptr) == 1) {
1141
1142                 type* SavedType;
1143
1144                 /* Reverse the order of evaluation */
1145                 unsigned flags = (SizeOf (lval2.e_tptr) == 1)? CF_CHAR : CF_INT;
1146                 RemoveCode (Mark2);
1147
1148                 /* Get a pointer to the array into the primary. We have changed
1149                  * e_tptr above but we need the original type to load the
1150                  * address, so restore it temporarily.
1151                  */
1152                 SavedType = lval->e_tptr;
1153                 lval->e_tptr = tptr1;
1154                 exprhs (CF_NONE, k, lval);
1155                 lval->e_tptr = SavedType;
1156
1157                 /* Add the variable */
1158                 if (rflags == E_MLOCAL) {
1159                     g_addlocal (flags, lval2.e_const);
1160                 } else {
1161                     flags |= GlobalModeFlags (lval2.e_flags);
1162                     g_addstatic (flags, lval2.e_name, lval2.e_const);
1163                 }
1164             } else {
1165                 if (lflags == E_MCONST) {
1166                     /* Constant numeric address. Just add it */
1167                     g_inc (CF_INT | CF_UNSIGNED, lval->e_const);
1168                 } else if (lflags == E_MLOCAL) {
1169                     /* Base address is a local variable address */
1170                     if (IsTypeArray (tptr1)) {
1171                         g_addaddr_local (CF_INT, lval->e_const);
1172                     } else {
1173                         g_addlocal (CF_PTR, lval->e_const);
1174                     }
1175                 } else {
1176                     /* Base address is a static variable address */
1177                     unsigned flags = CF_INT;
1178                     flags |= GlobalModeFlags (lval->e_flags);
1179                     if (IsTypeArray (tptr1)) {
1180                         g_addaddr_static (flags, lval->e_name, lval->e_const);
1181                     } else {
1182                         g_addstatic (flags, lval->e_name, lval->e_const);
1183                     }
1184                 }
1185             }
1186         }
1187     }
1188     lval->e_flags = E_MEXPR;
1189 end_array:
1190     ConsumeRBrack ();
1191     return !IsTypeArray (lval->e_tptr);
1192
1193 }
1194
1195
1196
1197 static int structref (int k, struct expent* lval)
1198 /* Process struct field after . or ->. */
1199 {
1200     ident Ident;
1201     SymEntry* Field;
1202     int flags;
1203
1204     /* Skip the token and check for an identifier */
1205     NextToken ();
1206     if (curtok != TOK_IDENT) {
1207         Error ("Identifier expected");
1208         lval->e_tptr = type_int;
1209         return 0;
1210     }
1211
1212     /* Get the symbol table entry and check for a struct field */
1213     strcpy (Ident, CurTok.Ident);
1214     NextToken ();
1215     Field = FindStructField (lval->e_tptr, Ident);
1216     if (Field == 0) {
1217         Error ("Struct/union has no field named `%s'", Ident);
1218         lval->e_tptr = type_int;
1219         return 0;
1220     }
1221
1222     /* If we have constant input data, the result is also constant */
1223     flags = lval->e_flags & ~E_MCTYPE;
1224     if (flags == E_MCONST ||
1225         (k == 0 && (flags == E_MLOCAL ||
1226                     (flags & E_MGLOBAL) != 0 ||
1227                     lval->e_flags  == E_MEOFFS))) {
1228         lval->e_const += Field->V.Offs;
1229     } else {
1230         if ((flags & E_MEXPR) == 0 || k != 0) {
1231             exprhs (CF_NONE, k, lval);
1232         }
1233         lval->e_const = Field->V.Offs;
1234         lval->e_flags = E_MEOFFS;
1235     }
1236     lval->e_tptr = Field->Type;
1237     return !IsTypeArray (Field->Type);
1238 }
1239
1240
1241
1242 static int hie11 (struct expent *lval)
1243 /* Handle compound types (structs and arrays) */
1244 {
1245     int k;
1246     type* tptr;
1247
1248
1249     k = primary (lval);
1250     if (curtok < TOK_LBRACK || curtok > TOK_PTR_REF) {
1251         /* Not for us */
1252         return k;
1253     }
1254
1255     while (1) {
1256
1257         if (curtok == TOK_LBRACK) {
1258
1259             /* Array reference */
1260             k = arrayref (k, lval);
1261
1262         } else if (curtok == TOK_LPAREN) {
1263
1264             /* Function call. Skip the opening parenthesis */
1265             NextToken ();
1266             tptr = lval->e_tptr;
1267             if (IsTypeFunc (tptr) || IsTypeFuncPtr (tptr)) {
1268                 if (IsTypeFuncPtr (tptr)) {
1269                     /* Pointer to function. Handle transparently */
1270                     exprhs (CF_NONE, k, lval);  /* Function pointer to A/X */
1271                     ++lval->e_tptr;             /* Skip T_PTR */
1272                     lval->e_flags |= E_MEXPR;
1273                 }
1274                 CallFunction (lval);
1275                 lval->e_flags = E_MEXPR;
1276                 lval->e_tptr += DECODE_SIZE + 1;        /* Set to result */
1277             } else {
1278                 Error ("Illegal function call");
1279             }
1280             k = 0;
1281
1282         } else if (curtok == TOK_DOT) {
1283
1284             if (!IsClassStruct (lval->e_tptr)) {
1285                 Error ("Struct expected");
1286             }
1287             k = structref (0, lval);
1288
1289         } else if (curtok == TOK_PTR_REF) {
1290
1291             tptr = lval->e_tptr;
1292             if (tptr[0] != T_PTR || (tptr[1] & T_STRUCT) == 0) {
1293                 Error ("Struct pointer expected");
1294             }
1295             k = structref (k, lval);
1296
1297         } else {
1298             return k;
1299         }
1300     }
1301 }
1302
1303
1304
1305 static void store (struct expent* lval)
1306 /* Store primary reg into this reference */
1307 {
1308     int f;
1309     unsigned flags;
1310
1311     f = lval->e_flags;
1312     flags = TypeOf (lval->e_tptr);
1313     if (f & E_MGLOBAL) {
1314         flags |= GlobalModeFlags (f);
1315         if (lval->e_test) {
1316             /* Just testing */
1317             flags |= CF_TEST;
1318         }
1319
1320         /* Generate code */
1321         g_putstatic (flags, lval->e_name, lval->e_const);
1322
1323     } else if (f & E_MLOCAL) {
1324         g_putlocal (flags, lval->e_const, 0);
1325     } else if (f == E_MEOFFS) {
1326         g_putind (flags, lval->e_const);
1327     } else if (f != E_MREG) {
1328         if (f & E_MEXPR) {
1329             g_putind (flags, 0);
1330         } else {
1331             /* Store into absolute address */
1332             g_putstatic (flags | CF_ABSOLUTE, lval->e_const, 0);
1333         }
1334     }
1335
1336     /* Assume that each one of the stores will invalidate CC */
1337     lval->e_test &= ~E_CC;
1338 }
1339
1340
1341
1342 static void pre_incdec (struct expent* lval, void (*inc) (unsigned, unsigned long))
1343 /* Handle --i and ++i */
1344 {
1345     int k;
1346     unsigned flags;
1347     unsigned long val;
1348
1349     NextToken ();
1350     if ((k = hie10 (lval)) == 0) {
1351         Error ("Invalid lvalue");
1352         return;
1353     }
1354
1355     /* Get the data type */
1356     flags = TypeOf (lval->e_tptr) | CF_FORCECHAR | CF_CONST;
1357
1358     /* Get the increment value in bytes */
1359     val = (lval->e_tptr [0] == T_PTR)? PSizeOf (lval->e_tptr) : 1;
1360
1361     /* We're currently only able to handle some adressing modes */
1362     if ((lval->e_flags & E_MGLOBAL) == 0 &&     /* Global address? */
1363         (lval->e_flags & E_MLOCAL) == 0  &&     /* Local address? */
1364         (lval->e_flags & E_MCONST) == 0  &&     /* Constant address? */
1365         (lval->e_flags & E_MEXPR) == 0) {       /* Address in a/x? */
1366
1367         /* Use generic code. Push the address if needed */
1368         PushAddr (lval);
1369
1370         /* Fetch the value */
1371         exprhs (CF_NONE, k, lval);
1372
1373         /* Increment value in primary */
1374         inc (flags, val);
1375
1376         /* Store the result back */
1377         store (lval);
1378
1379     } else {
1380
1381         /* Special code for some addressing modes - use the special += ops */
1382         if (lval->e_flags & E_MGLOBAL) {
1383             flags |= GlobalModeFlags (lval->e_flags);
1384             if (inc == g_inc) {
1385                 g_addeqstatic (flags, lval->e_name, lval->e_const, val);
1386             } else {
1387                 g_subeqstatic (flags, lval->e_name, lval->e_const, val);
1388             }
1389         } else if (lval->e_flags & E_MLOCAL) {
1390             /* ref to localvar */
1391             if (inc == g_inc) {
1392                 g_addeqlocal (flags, lval->e_const, val);
1393             } else {
1394                 g_subeqlocal (flags, lval->e_const, val);
1395             }
1396         } else if (lval->e_flags & E_MCONST) {
1397             /* ref to absolute address */
1398             flags |= CF_ABSOLUTE;
1399             if (inc == g_inc) {
1400                 g_addeqstatic (flags, lval->e_const, 0, val);
1401             } else {
1402                 g_subeqstatic (flags, lval->e_const, 0, val);
1403             }
1404         } else if (lval->e_flags & E_MEXPR) {
1405             /* Address in a/x, check if we have an offset */
1406             unsigned Offs = (lval->e_flags == E_MEOFFS)? lval->e_const : 0;
1407             if (inc == g_inc) {
1408                 g_addeqind (flags, Offs, val);
1409             } else {
1410                 g_subeqind (flags, Offs, val);
1411             }
1412         } else {
1413             Internal ("Invalid addressing mode");
1414         }
1415
1416     }
1417
1418     /* Result is an expression */
1419     lval->e_flags = E_MEXPR;
1420 }
1421
1422
1423
1424 static void post_incdec (struct expent *lval, int k, void (*inc) (unsigned, unsigned long))
1425 /* Handle i-- and i++ */
1426 {
1427     unsigned flags;
1428
1429     NextToken ();
1430     if (k == 0) {
1431         Error ("Invalid lvalue");
1432         return;
1433     }
1434
1435     /* Get the data type */
1436     flags = TypeOf (lval->e_tptr);
1437
1438     /* Push the address if needed */
1439     PushAddr (lval);
1440
1441     /* Fetch the value and save it (since it's the result of the expression) */
1442     exprhs (CF_NONE, 1, lval);
1443     g_save (flags | CF_FORCECHAR);
1444
1445     /* If we have a pointer expression, increment by the size of the type */
1446     if (lval->e_tptr[0] == T_PTR) {
1447         inc (flags | CF_CONST | CF_FORCECHAR, SizeOf (lval->e_tptr + 1));
1448     } else {
1449         inc (flags | CF_CONST | CF_FORCECHAR, 1);
1450     }
1451
1452     /* Store the result back */
1453     store (lval);
1454
1455     /* Restore the original value */
1456     g_restore (flags | CF_FORCECHAR);
1457     lval->e_flags = E_MEXPR;
1458 }
1459
1460
1461
1462 static void unaryop (int tok, struct expent* lval)
1463 /* Handle unary -/+ and ~ */
1464 {
1465     int k;
1466     unsigned flags;
1467
1468     NextToken ();
1469     k = hie10 (lval);
1470     if (k == 0 && lval->e_flags & E_MCONST) {
1471         /* Value is constant */
1472         switch (tok) {
1473             case TOK_MINUS: lval->e_const =     -lval->e_const; break;
1474             case TOK_PLUS:                                      break;
1475             case TOK_COMP:  lval->e_const = ~lval->e_const;     break;
1476             default:        Internal ("Unexpected token: %d", tok);
1477         }
1478     } else {
1479         /* Value is not constant */
1480         exprhs (CF_NONE, k, lval);
1481
1482         /* Get the type of the expression */
1483         flags = TypeOf (lval->e_tptr);
1484
1485         /* Handle the operation */
1486         switch (tok) {
1487             case TOK_MINUS: g_neg (flags);  break;
1488             case TOK_PLUS:                  break;
1489             case TOK_COMP:  g_com (flags);  break;
1490             default:    Internal ("Unexpected token: %d", tok);
1491         }
1492         lval->e_flags = E_MEXPR;
1493     }
1494 }
1495
1496
1497
1498 static int typecast (struct expent* lval)
1499 /* Handle an explicit cast */
1500 {
1501     int k;
1502     type Type[MAXTYPELEN];
1503
1504     /* Skip the left paren */
1505     NextToken ();
1506
1507     /* Read the type */
1508     ParseType (Type);
1509
1510     /* Closing paren */
1511     ConsumeRParen ();
1512
1513     /* Read the expression we have to cast */
1514     k = hie10 (lval);
1515
1516     /* If the expression is a function, treat it as pointer-to-function */
1517     if (IsTypeFunc (lval->e_tptr)) {
1518         lval->e_tptr = PointerTo (lval->e_tptr);
1519     }
1520
1521     /* Check for a constant on the right side */
1522     if (k == 0 && lval->e_flags == E_MCONST) {
1523
1524         /* A cast of a constant to something else. If the new type is an int,
1525          * be sure to handle the size extension correctly. If the new type is
1526          * not an int, the cast is implementation specific anyway, so leave
1527          * the value alone.
1528          */
1529         if (IsClassInt (Type)) {
1530
1531             /* Get the current and new size of the value */
1532             unsigned OldSize = SizeOf (lval->e_tptr);
1533             unsigned NewSize = SizeOf (Type);
1534             unsigned OldBits = OldSize * 8;
1535             unsigned NewBits = NewSize * 8;
1536
1537             /* Check if the new datatype will have a smaller range */
1538             if (NewSize < OldSize) {
1539
1540                 /* Cut the value to the new size */
1541                 lval->e_const &= (0xFFFFFFFFUL >> (32 - NewBits));
1542
1543                 /* If the new value is signed, sign extend the value */
1544                 if (!IsSignUnsigned (Type)) {
1545                     lval->e_const |= ((~0L) << NewBits);
1546                 }
1547
1548             } else if (NewSize > OldSize) {
1549
1550                 /* Sign extend the value if needed */
1551                 if (!IsSignUnsigned (Type) && !IsSignUnsigned (lval->e_tptr)) {
1552                     if (lval->e_const & (0x01UL << (OldBits-1))) {
1553                         lval->e_const |= ((~0L) << OldBits);
1554                     }
1555                 }
1556             }
1557         }
1558
1559     } else {
1560
1561         /* Not a constant. Be sure to ignore casts to void */
1562         if (!IsTypeVoid (Type)) {
1563
1564             /* If the size does not change, leave the value alone. Otherwise,
1565              * we have to load the value into the primary and generate code to
1566              * cast the value in the primary register.
1567              */
1568             if (SizeOf (Type) != SizeOf (lval->e_tptr)) {
1569
1570                 /* Load the value into the primary */
1571                 exprhs (CF_NONE, k, lval);
1572
1573                 /* Mark the lhs as const to avoid a manipulation of TOS */
1574                 g_typecast (TypeOf (Type) | CF_CONST, TypeOf (lval->e_tptr));
1575
1576                 /* Value is now in primary */
1577                 lval->e_flags = E_MEXPR;
1578                 k = 0;
1579             }
1580         }
1581     }
1582
1583     /* In any case, use the new type */
1584     lval->e_tptr = TypeDup (Type);
1585
1586     /* Done */
1587     return k;
1588 }
1589
1590
1591
1592 static int hie10 (struct expent* lval)
1593 /* Handle ++, --, !, unary - etc. */
1594 {
1595     int k;
1596     type* t;
1597
1598     switch (curtok) {
1599
1600         case TOK_INC:
1601             pre_incdec (lval, g_inc);
1602             return 0;
1603
1604         case TOK_DEC:
1605             pre_incdec (lval, g_dec);
1606             return 0;
1607
1608         case TOK_PLUS:
1609         case TOK_MINUS:
1610         case TOK_COMP:
1611             unaryop (curtok, lval);
1612             return 0;
1613
1614         case TOK_BOOL_NOT:
1615             NextToken ();
1616             if (evalexpr (CF_NONE, hie10, lval) == 0) {
1617                 /* Constant expression */
1618                 lval->e_const = !lval->e_const;
1619             } else {
1620                 g_bneg (TypeOf (lval->e_tptr));
1621                 lval->e_test |= E_CC;                   /* bneg will set cc */
1622                 lval->e_flags = E_MEXPR;                /* say it's an expr */
1623             }
1624             return 0;                           /* expr not storable */
1625
1626         case TOK_STAR:
1627             NextToken ();
1628             if (evalexpr (CF_NONE, hie10, lval) != 0) {
1629                 /* Expression is not const, indirect value loaded into primary */
1630                 lval->e_flags = E_MEXPR;
1631                 lval->e_const = 0;              /* Offset is zero now */
1632             }
1633             t = lval->e_tptr;
1634             if (IsClassPtr (t)) {
1635                 lval->e_tptr = Indirect (t);
1636             } else {
1637                 Error ("Illegal indirection");
1638             }
1639             return 1;
1640
1641         case TOK_AND:
1642             NextToken ();
1643             k = hie10 (lval);
1644             /* The & operator may be applied to any lvalue, and it may be
1645              * applied to functions, even if they're no lvalues.
1646              */
1647             if (k == 0 && !IsTypeFunc (lval->e_tptr)) {
1648                 /* Allow the & operator with an array */
1649                 if (!IsTypeArray (lval->e_tptr)) {
1650                     Error ("Illegal address");
1651                 }
1652             } else {
1653                 t = TypeAlloc (TypeLen (lval->e_tptr) + 2);
1654                 t [0] = T_PTR;
1655                 TypeCpy (t + 1, lval->e_tptr);
1656                 lval->e_tptr = t;
1657             }
1658             return 0;
1659
1660         case TOK_SIZEOF:
1661             NextToken ();
1662             if (istypeexpr ()) {
1663                 type Type[MAXTYPELEN];
1664                 NextToken ();
1665                 lval->e_const = SizeOf (ParseType (Type));
1666                 ConsumeRParen ();
1667             } else {
1668                 /* Remember the output queue pointer */
1669                 CodeMark Mark = GetCodePos ();
1670                 hie10 (lval);
1671                 lval->e_const = SizeOf (lval->e_tptr);
1672                 /* Remove any generated code */
1673                 RemoveCode (Mark);
1674             }
1675             lval->e_flags = E_MCONST | E_TCONST;
1676             lval->e_tptr = type_uint;
1677             lval->e_test &= ~E_CC;
1678             return 0;
1679
1680         default:
1681             if (istypeexpr ()) {
1682                 /* A cast */
1683                 return typecast (lval);
1684             }
1685     }
1686
1687     k = hie11 (lval);
1688     switch (curtok) {
1689         case TOK_INC:
1690             post_incdec (lval, k, g_inc);
1691             return 0;
1692
1693         case TOK_DEC:
1694             post_incdec (lval, k, g_dec);
1695             return 0;
1696
1697         default:
1698             return k;
1699     }
1700 }
1701
1702
1703
1704 static int hie_internal (GenDesc** ops,         /* List of generators */
1705                          struct expent* lval,   /* parent expr's lval */
1706                          int (*hienext) (struct expent*),
1707                          int* UsedGen)          /* next higher level */
1708 /* Helper function */
1709 {
1710     int k;
1711     struct expent lval2;
1712     CodeMark Mark1;
1713     CodeMark Mark2;
1714     GenDesc* Gen;
1715     token_t tok;                        /* The operator token */
1716     unsigned ltype, type;
1717     int rconst;                         /* Operand is a constant */
1718
1719
1720     k = hienext (lval);
1721
1722     *UsedGen = 0;
1723     while ((Gen = FindGen (curtok, ops)) != 0) {
1724
1725         /* Tell the caller that we handled it's ops */
1726         *UsedGen = 1;
1727
1728         /* All operators that call this function expect an int on the lhs */
1729         if (!IsClassInt (lval->e_tptr)) {
1730             Error ("Integer expression expected");
1731         }
1732
1733         /* Remember the operator token, then skip it */
1734         tok = curtok;
1735         NextToken ();
1736
1737         /* Get the lhs on stack */
1738         Mark1 = GetCodePos ();
1739         ltype = TypeOf (lval->e_tptr);
1740         if (k == 0 && lval->e_flags == E_MCONST) {
1741             /* Constant value */
1742             Mark2 = GetCodePos ();
1743             g_push (ltype | CF_CONST, lval->e_const);
1744         } else {
1745             /* Value not constant */
1746             exprhs (CF_NONE, k, lval);
1747             Mark2 = GetCodePos ();
1748             g_push (ltype, 0);
1749         }
1750
1751         /* Get the right hand side */
1752         rconst = (evalexpr (CF_NONE, hienext, &lval2) == 0);
1753
1754         /* Check the type of the rhs */
1755         if (!IsClassInt (lval2.e_tptr)) {
1756             Error ("Integer expression expected");
1757         }
1758
1759         /* Check for const operands */
1760         if (k == 0 && lval->e_flags == E_MCONST && rconst) {
1761
1762             /* Both operands are constant, remove the generated code */
1763             RemoveCode (Mark1);
1764             pop (ltype);
1765
1766             /* Evaluate the result */
1767             lval->e_const = kcalc (tok, lval->e_const, lval2.e_const);
1768
1769             /* Get the type of the result */
1770             lval->e_tptr = promoteint (lval->e_tptr, lval2.e_tptr);
1771
1772         } else {
1773
1774             /* If the right hand side is constant, and the generator function
1775              * expects the lhs in the primary, remove the push of the primary
1776              * now.
1777              */
1778             unsigned rtype = TypeOf (lval2.e_tptr);
1779             type = 0;
1780             if (rconst) {
1781                 /* Second value is constant - check for div */
1782                 type |= CF_CONST;
1783                 rtype |= CF_CONST;
1784                 if (tok == TOK_DIV && lval2.e_const == 0) {
1785                     Error ("Division by zero");
1786                 } else if (tok == TOK_MOD && lval2.e_const == 0) {
1787                     Error ("Modulo operation with zero");
1788                 }
1789                 if ((Gen->Flags & GEN_NOPUSH) != 0) {
1790                     RemoveCode (Mark2);
1791                     pop (ltype);
1792                     ltype |= CF_REG;    /* Value is in register */
1793                 }
1794             }
1795
1796             /* Determine the type of the operation result. */
1797             type |= g_typeadjust (ltype, rtype);
1798             lval->e_tptr = promoteint (lval->e_tptr, lval2.e_tptr);
1799
1800             /* Generate code */
1801             Gen->Func (type, lval2.e_const);
1802             lval->e_flags = E_MEXPR;
1803         }
1804
1805         /* We have a rvalue now */
1806         k = 0;
1807     }
1808
1809     return k;
1810 }
1811
1812
1813
1814 static int hie_compare (GenDesc** ops,          /* List of generators */
1815                         struct expent* lval,    /* parent expr's lval */
1816                         int (*hienext) (struct expent*))
1817 /* Helper function for the compare operators */
1818 {
1819     int k;
1820     struct expent lval2;
1821     CodeMark Mark1;
1822     CodeMark Mark2;
1823     GenDesc* Gen;
1824     token_t tok;                        /* The operator token */
1825     unsigned ltype;
1826     int rconst;                         /* Operand is a constant */
1827
1828
1829     k = hienext (lval);
1830
1831     while ((Gen = FindGen (curtok, ops)) != 0) {
1832
1833         /* Remember the operator token, then skip it */
1834         tok = curtok;
1835         NextToken ();
1836
1837         /* Get the lhs on stack */
1838         Mark1 = GetCodePos ();
1839         ltype = TypeOf (lval->e_tptr);
1840         if (k == 0 && lval->e_flags == E_MCONST) {
1841             /* Constant value */
1842             Mark2 = GetCodePos ();
1843             g_push (ltype | CF_CONST, lval->e_const);
1844         } else {
1845             /* Value not constant */
1846             exprhs (CF_NONE, k, lval);
1847             Mark2 = GetCodePos ();
1848             g_push (ltype, 0);
1849         }
1850
1851         /* Get the right hand side */
1852         rconst = (evalexpr (CF_NONE, hienext, &lval2) == 0);
1853
1854         /* Make sure, the types are compatible */
1855         if (IsClassInt (lval->e_tptr)) {
1856             if (!IsClassInt (lval2.e_tptr) && !(IsClassPtr(lval2.e_tptr) && IsNullPtr(lval))) {
1857                 Error ("Incompatible types");
1858             }
1859         } else if (IsClassPtr (lval->e_tptr)) {
1860             if (IsClassPtr (lval2.e_tptr)) {
1861                 /* Both pointers are allowed in comparison if they point to
1862                  * the same type, or if one of them is a void pointer.
1863                  */
1864                 type* left  = Indirect (lval->e_tptr);
1865                 type* right = Indirect (lval2.e_tptr);
1866                 if (TypeCmp (left, right) < TC_EQUAL && *left != T_VOID && *right != T_VOID) {
1867                     /* Incomatible pointers */
1868                     Error ("Incompatible types");
1869                 }
1870             } else if (!IsNullPtr (&lval2)) {
1871                 Error ("Incompatible types");
1872             }
1873         }
1874
1875         /* Check for const operands */
1876         if (k == 0 && lval->e_flags == E_MCONST && rconst) {
1877
1878             /* Both operands are constant, remove the generated code */
1879             RemoveCode (Mark1);
1880             pop (ltype);
1881
1882             /* Evaluate the result */
1883             lval->e_const = kcalc (tok, lval->e_const, lval2.e_const);
1884
1885         } else {
1886
1887             /* If the right hand side is constant, and the generator function
1888              * expects the lhs in the primary, remove the push of the primary
1889              * now.
1890              */
1891             unsigned flags = 0;
1892             if (rconst) {
1893                 flags |= CF_CONST;
1894                 if ((Gen->Flags & GEN_NOPUSH) != 0) {
1895                     RemoveCode (Mark2);
1896                     pop (ltype);
1897                     ltype |= CF_REG;    /* Value is in register */
1898                 }
1899             }
1900
1901             /* Determine the type of the operation result. If the left
1902              * operand is of type char and the right is a constant, or
1903              * if both operands are of type char, we will encode the
1904              * operation as char operation. Otherwise the default
1905              * promotions are used.
1906              */
1907             if (IsTypeChar (lval->e_tptr) && (IsTypeChar (lval2.e_tptr) || rconst)) {
1908                 flags |= CF_CHAR;
1909                 if (IsSignUnsigned (lval->e_tptr) || IsSignUnsigned (lval2.e_tptr)) {
1910                     flags |= CF_UNSIGNED;
1911                 }
1912                 if (rconst) {
1913                     flags |= CF_FORCECHAR;
1914                 }
1915             } else {
1916                 unsigned rtype = TypeOf (lval2.e_tptr) | (flags & CF_CONST);
1917                 flags |= g_typeadjust (ltype, rtype);
1918             }
1919
1920             /* Generate code */
1921             Gen->Func (flags, lval2.e_const);
1922             lval->e_flags = E_MEXPR;
1923         }
1924
1925         /* Result type is always int */
1926         lval->e_tptr = type_int;
1927
1928         /* We have a rvalue now, condition codes are set */
1929         k = 0;
1930         lval->e_test |= E_CC;
1931     }
1932
1933     return k;
1934 }
1935
1936
1937
1938 static int hie9 (struct expent *lval)
1939 /* Process * and / operators. */
1940 {
1941     static GenDesc* hie9_ops [] = {
1942         &GenMUL, &GenDIV, &GenMOD, 0
1943     };
1944     int UsedGen;
1945
1946     return hie_internal (hie9_ops, lval, hie10, &UsedGen);
1947 }
1948
1949
1950
1951 static void parseadd (int k, struct expent* lval)
1952 /* Parse an expression with the binary plus operator. lval contains the
1953  * unprocessed left hand side of the expression and will contain the
1954  * result of the expression on return.
1955  */
1956 {
1957     struct expent lval2;
1958     unsigned flags;             /* Operation flags */
1959     CodeMark Mark;              /* Remember code position */
1960     type* lhst;                 /* Type of left hand side */
1961     type* rhst;                 /* Type of right hand side */
1962
1963
1964     /* Skip the PLUS token */
1965     NextToken ();
1966
1967     /* Get the left hand side type, initialize operation flags */
1968     lhst = lval->e_tptr;
1969     flags = 0;
1970
1971     /* Check for constness on both sides */
1972     if (k == 0 && lval->e_flags == E_MCONST) {
1973
1974         /* The left hand side is a constant. Good. Get rhs */
1975         if (evalexpr (CF_NONE, hie9, &lval2) == 0) {
1976
1977             /* Right hand side is also constant. Get the rhs type */
1978             rhst = lval2.e_tptr;
1979
1980             /* Both expressions are constants. Check for pointer arithmetic */
1981             if (IsClassPtr (lhst) && IsClassInt (rhst)) {
1982                 /* Left is pointer, right is int, must scale rhs */
1983                 lval->e_const = lval->e_const + lval2.e_const * PSizeOf (lhst);
1984                 /* Result type is a pointer */
1985             } else if (IsClassInt (lhst) && IsClassPtr (rhst)) {
1986                 /* Left is int, right is pointer, must scale lhs */
1987                 lval->e_const = lval->e_const * PSizeOf (rhst) + lval2.e_const;
1988                 /* Result type is a pointer */
1989                 lval->e_tptr = lval2.e_tptr;
1990             } else if (IsClassInt (lhst) && IsClassInt (rhst)) {
1991                 /* Integer addition */
1992                 lval->e_const += lval2.e_const;
1993                 typeadjust (lval, &lval2, 1);
1994             } else {
1995                 /* OOPS */
1996                 Error ("Invalid operands for binary operator `+'");
1997             }
1998
1999             /* Result is constant, condition codes not set */
2000             lval->e_test = E_MCONST;
2001
2002         } else {
2003
2004             /* lhs is constant, rhs is not. Get the rhs type. */
2005             rhst = lval2.e_tptr;
2006
2007             /* Check for pointer arithmetic */
2008             if (IsClassPtr (lhst) && IsClassInt (rhst)) {
2009                 /* Left is pointer, right is int, must scale rhs */
2010                 g_scale (CF_INT, PSizeOf (lhst));
2011                 /* Operate on pointers, result type is a pointer */
2012                 flags = CF_PTR;
2013             } else if (IsClassInt (lhst) && IsClassPtr (rhst)) {
2014                 /* Left is int, right is pointer, must scale lhs */
2015                 lval->e_const *= PSizeOf (rhst);
2016                 /* Operate on pointers, result type is a pointer */
2017                 flags = CF_PTR;
2018                 lval->e_tptr = lval2.e_tptr;
2019             } else if (IsClassInt (lhst) && IsClassInt (rhst)) {
2020                 /* Integer addition */
2021                 flags = typeadjust (lval, &lval2, 1);
2022             } else {
2023                 /* OOPS */
2024                 Error ("Invalid operands for binary operator `+'");
2025             }
2026
2027             /* Generate code for the add */
2028             g_inc (flags | CF_CONST, lval->e_const);
2029
2030             /* Result is in primary register */
2031             lval->e_flags = E_MEXPR;
2032             lval->e_test &= ~E_CC;
2033
2034         }
2035
2036     } else {
2037
2038         /* Left hand side is not constant. Get the value onto the stack. */
2039         exprhs (CF_NONE, k, lval);              /* --> primary register */
2040         Mark = GetCodePos ();
2041         g_push (TypeOf (lval->e_tptr), 0);      /* --> stack */
2042
2043         /* Evaluate the rhs */
2044         if (evalexpr (CF_NONE, hie9, &lval2) == 0) {
2045
2046             /* Right hand side is a constant. Get the rhs type */
2047             rhst = lval2.e_tptr;
2048
2049             /* Remove pushed value from stack */
2050             RemoveCode (Mark);
2051             pop (TypeOf (lval->e_tptr));
2052
2053             /* Check for pointer arithmetic */
2054             if (IsClassPtr (lhst) && IsClassInt (rhst)) {
2055                 /* Left is pointer, right is int, must scale rhs */
2056                 lval2.e_const *= PSizeOf (lhst);
2057                 /* Operate on pointers, result type is a pointer */
2058                 flags = CF_PTR;
2059             } else if (IsClassInt (lhst) && IsClassPtr (rhst)) {
2060                 /* Left is int, right is pointer, must scale lhs (ptr only) */
2061                 g_scale (CF_INT | CF_CONST, PSizeOf (rhst));
2062                 /* Operate on pointers, result type is a pointer */
2063                 flags = CF_PTR;
2064                 lval->e_tptr = lval2.e_tptr;
2065             } else if (IsClassInt (lhst) && IsClassInt (rhst)) {
2066                 /* Integer addition */
2067                 flags = typeadjust (lval, &lval2, 1);
2068             } else {
2069                 /* OOPS */
2070                 Error ("Invalid operands for binary operator `+'");
2071             }
2072
2073             /* Generate code for the add */
2074             g_inc (flags | CF_CONST, lval2.e_const);
2075
2076             /* Result is in primary register */
2077             lval->e_flags = E_MEXPR;
2078             lval->e_test &= ~E_CC;
2079
2080         } else {
2081
2082             /* lhs and rhs are not constant. Get the rhs type. */
2083             rhst = lval2.e_tptr;
2084
2085             /* Check for pointer arithmetic */
2086             if (IsClassPtr (lhst) && IsClassInt (rhst)) {
2087                 /* Left is pointer, right is int, must scale rhs */
2088                 g_scale (CF_INT, PSizeOf (lhst));
2089                 /* Operate on pointers, result type is a pointer */
2090                 flags = CF_PTR;
2091             } else if (IsClassInt (lhst) && IsClassPtr (rhst)) {
2092                 /* Left is int, right is pointer, must scale lhs */
2093                 g_tosint (TypeOf (rhst));       /* Make sure, TOS is int */
2094                 g_swap (CF_INT);                /* Swap TOS and primary */
2095                 g_scale (CF_INT, PSizeOf (rhst));
2096                 /* Operate on pointers, result type is a pointer */
2097                 flags = CF_PTR;
2098                 lval->e_tptr = lval2.e_tptr;
2099             } else if (IsClassInt (lhst) && IsClassInt (rhst)) {
2100                 /* Integer addition */
2101                 flags = typeadjust (lval, &lval2, 0);
2102             } else {
2103                 /* OOPS */
2104                 Error ("Invalid operands for binary operator `+'");
2105             }
2106
2107             /* Generate code for the add */
2108             g_add (flags, 0);
2109
2110             /* Result is in primary register */
2111             lval->e_flags = E_MEXPR;
2112             lval->e_test &= ~E_CC;
2113
2114         }
2115
2116     }
2117 }
2118
2119
2120
2121 static void parsesub (int k, struct expent* lval)
2122 /* Parse an expression with the binary minus operator. lval contains the
2123  * unprocessed left hand side of the expression and will contain the
2124  * result of the expression on return.
2125  */
2126 {
2127     struct expent lval2;
2128     unsigned flags;             /* Operation flags */
2129     type* lhst;                 /* Type of left hand side */
2130     type* rhst;                 /* Type of right hand side */
2131     CodeMark Mark1;             /* Save position of output queue */
2132     CodeMark Mark2;             /* Another position in the queue */
2133     int rscale;                 /* Scale factor for the result */
2134
2135
2136     /* Skip the MINUS token */
2137     NextToken ();
2138
2139     /* Get the left hand side type, initialize operation flags */
2140     lhst = lval->e_tptr;
2141     flags = 0;
2142     rscale = 1;                 /* Scale by 1, that is, don't scale */
2143
2144     /* Remember the output queue position, then bring the value onto the stack */
2145     Mark1 = GetCodePos ();
2146     exprhs (CF_NONE, k, lval);  /* --> primary register */
2147     Mark2 = GetCodePos ();
2148     g_push (TypeOf (lhst), 0);  /* --> stack */
2149
2150     /* Parse the right hand side */
2151     if (evalexpr (CF_NONE, hie9, &lval2) == 0) {
2152
2153         /* The right hand side is constant. Get the rhs type. */
2154         rhst = lval2.e_tptr;
2155
2156         /* Check left hand side */
2157         if (k == 0 && lval->e_flags & E_MCONST) {
2158
2159             /* Both sides are constant, remove generated code */
2160             RemoveCode (Mark1);
2161             pop (TypeOf (lhst));        /* Clean up the stack */
2162
2163             /* Check for pointer arithmetic */
2164             if (IsClassPtr (lhst) && IsClassInt (rhst)) {
2165                 /* Left is pointer, right is int, must scale rhs */
2166                 lval->e_const -= lval2.e_const * PSizeOf (lhst);
2167                 /* Operate on pointers, result type is a pointer */
2168             } else if (IsClassPtr (lhst) && IsClassPtr (rhst)) {
2169                 /* Left is pointer, right is pointer, must scale result */
2170                 if (TypeCmp (Indirect (lhst), Indirect (rhst)) < TC_EQUAL) {
2171                     Error ("Incompatible pointer types");
2172                 } else {
2173                     lval->e_const = (lval->e_const - lval2.e_const) / PSizeOf (lhst);
2174                 }
2175                 /* Operate on pointers, result type is an integer */
2176                 lval->e_tptr = type_int;
2177             } else if (IsClassInt (lhst) && IsClassInt (rhst)) {
2178                 /* Integer subtraction */
2179                 typeadjust (lval, &lval2, 1);
2180                 lval->e_const -= lval2.e_const;
2181             } else {
2182                 /* OOPS */
2183                 Error ("Invalid operands for binary operator `-'");
2184             }
2185
2186             /* Result is constant, condition codes not set */
2187             lval->e_flags = E_MCONST;
2188             lval->e_test &= ~E_CC;
2189
2190         } else {
2191
2192             /* Left hand side is not constant, right hand side is.
2193              * Remove pushed value from stack.
2194              */
2195             RemoveCode (Mark2);
2196             pop (TypeOf (lhst));
2197
2198             if (IsClassPtr (lhst) && IsClassInt (rhst)) {
2199                 /* Left is pointer, right is int, must scale rhs */
2200                 lval2.e_const *= PSizeOf (lhst);
2201                 /* Operate on pointers, result type is a pointer */
2202                 flags = CF_PTR;
2203             } else if (IsClassPtr (lhst) && IsClassPtr (rhst)) {
2204                 /* Left is pointer, right is pointer, must scale result */
2205                 if (TypeCmp (Indirect (lhst), Indirect (rhst)) < TC_EQUAL) {
2206                     Error ("Incompatible pointer types");
2207                 } else {
2208                     rscale = PSizeOf (lhst);
2209                 }
2210                 /* Operate on pointers, result type is an integer */
2211                 flags = CF_PTR;
2212                 lval->e_tptr = type_int;
2213             } else if (IsClassInt (lhst) && IsClassInt (rhst)) {
2214                 /* Integer subtraction */
2215                 flags = typeadjust (lval, &lval2, 1);
2216             } else {
2217                 /* OOPS */
2218                 Error ("Invalid operands for binary operator `-'");
2219             }
2220
2221             /* Do the subtraction */
2222             g_dec (flags | CF_CONST, lval2.e_const);
2223
2224             /* If this was a pointer subtraction, we must scale the result */
2225             if (rscale != 1) {
2226                 g_scale (flags, -rscale);
2227             }
2228
2229             /* Result is in primary register */
2230             lval->e_flags = E_MEXPR;
2231             lval->e_test &= ~E_CC;
2232
2233         }
2234
2235     } else {
2236
2237         /* Right hand side is not constant. Get the rhs type. */
2238         rhst = lval2.e_tptr;
2239
2240         /* Check for pointer arithmetic */
2241         if (IsClassPtr (lhst) && IsClassInt (rhst)) {
2242             /* Left is pointer, right is int, must scale rhs */
2243             g_scale (CF_INT, PSizeOf (lhst));
2244             /* Operate on pointers, result type is a pointer */
2245             flags = CF_PTR;
2246         } else if (IsClassPtr (lhst) && IsClassPtr (rhst)) {
2247             /* Left is pointer, right is pointer, must scale result */
2248             if (TypeCmp (Indirect (lhst), Indirect (rhst)) < TC_EQUAL) {
2249                 Error ("Incompatible pointer types");
2250             } else {
2251                 rscale = PSizeOf (lhst);
2252             }
2253             /* Operate on pointers, result type is an integer */
2254             flags = CF_PTR;
2255             lval->e_tptr = type_int;
2256         } else if (IsClassInt (lhst) && IsClassInt (rhst)) {
2257             /* Integer subtraction. If the left hand side descriptor says that
2258              * the lhs is const, we have to remove this mark, since this is no
2259              * longer true, lhs is on stack instead.
2260              */
2261             if (lval->e_flags == E_MCONST) {
2262                 lval->e_flags = E_MEXPR;
2263             }
2264             /* Adjust operand types */
2265             flags = typeadjust (lval, &lval2, 0);
2266         } else {
2267             /* OOPS */
2268             Error ("Invalid operands for binary operator `-'");
2269         }
2270
2271         /* Generate code for the sub (the & is a hack here) */
2272         g_sub (flags & ~CF_CONST, 0);
2273
2274         /* If this was a pointer subtraction, we must scale the result */
2275         if (rscale != 1) {
2276             g_scale (flags, -rscale);
2277         }
2278
2279         /* Result is in primary register */
2280         lval->e_flags = E_MEXPR;
2281         lval->e_test &= ~E_CC;
2282     }
2283 }
2284
2285
2286
2287 static int hie8 (struct expent* lval)
2288 /* Process + and - binary operators. */
2289 {
2290     int k = hie9 (lval);
2291     while (curtok == TOK_PLUS || curtok == TOK_MINUS) {
2292
2293         if (curtok == TOK_PLUS) {
2294             parseadd (k, lval);
2295         } else {
2296             parsesub (k, lval);
2297         }
2298         k = 0;
2299     }
2300     return k;
2301 }
2302
2303
2304
2305
2306 static int hie7 (struct expent *lval)
2307 /* Parse << and >>. */
2308 {
2309     static GenDesc* hie7_ops [] = {
2310         &GenASL, &GenASR, 0
2311     };
2312     int UsedGen;
2313
2314     return hie_internal (hie7_ops, lval, hie8, &UsedGen);
2315 }
2316
2317
2318
2319 static int hie6 (struct expent *lval)
2320 /* process greater-than type comparators */
2321 {
2322     static GenDesc* hie6_ops [] = {
2323         &GenLT, &GenLE, &GenGE, &GenGT, 0
2324     };
2325     return hie_compare (hie6_ops, lval, hie7);
2326 }
2327
2328
2329
2330 static int hie5 (struct expent *lval)
2331 {
2332     static GenDesc* hie5_ops[] = {
2333         &GenEQ, &GenNE, 0
2334     };
2335     return hie_compare (hie5_ops, lval, hie6);
2336 }
2337
2338
2339
2340 static int hie4 (struct expent* lval)
2341 /* Handle & (bitwise and) */
2342 {
2343     static GenDesc* hie4_ops [] = {
2344         &GenAND, 0
2345     };
2346     int UsedGen;
2347
2348     return hie_internal (hie4_ops, lval, hie5, &UsedGen);
2349 }
2350
2351
2352
2353 static int hie3 (struct expent *lval)
2354 /* Handle ^ (bitwise exclusive or) */
2355 {
2356     static GenDesc* hie3_ops [] = {
2357         &GenXOR, 0
2358     };
2359     int UsedGen;
2360
2361     return hie_internal (hie3_ops, lval, hie4, &UsedGen);
2362 }
2363
2364
2365
2366 static int hie2 (struct expent *lval)
2367 /* Handle | (bitwise or) */
2368 {
2369     static GenDesc* hie2_ops [] = {
2370         &GenOR, 0
2371     };
2372     int UsedGen;
2373
2374     return hie_internal (hie2_ops, lval, hie3, &UsedGen);
2375 }
2376
2377
2378
2379 static int hieAnd (struct expent* lval, unsigned TrueLab, int* BoolOp)
2380 /* Process "exp && exp" */
2381 {
2382     int k;
2383     int lab;
2384     struct expent lval2;
2385
2386     k = hie2 (lval);
2387     if (curtok == TOK_BOOL_AND) {
2388
2389         /* Tell our caller that we're evaluating a boolean */
2390         *BoolOp = 1;
2391
2392         /* Get a label that we will use for false expressions */
2393         lab = GetLabel ();
2394
2395         /* If the expr hasn't set condition codes, set the force-test flag */
2396         if ((lval->e_test & E_CC) == 0) {
2397             lval->e_test |= E_FORCETEST;
2398         }
2399
2400         /* Load the value */
2401         exprhs (CF_FORCECHAR, k, lval);
2402
2403         /* Generate the jump */
2404         g_falsejump (CF_NONE, lab);
2405
2406         /* Parse more boolean and's */
2407         while (curtok == TOK_BOOL_AND) {
2408
2409             /* Skip the && */
2410             NextToken ();
2411
2412             /* Get rhs */
2413             k = hie2 (&lval2);
2414             if ((lval2.e_test & E_CC) == 0) {
2415                 lval2.e_test |= E_FORCETEST;
2416             }
2417             exprhs (CF_FORCECHAR, k, &lval2);
2418
2419             /* Do short circuit evaluation */
2420             if (curtok == TOK_BOOL_AND) {
2421                 g_falsejump (CF_NONE, lab);
2422             } else {
2423                 /* Last expression - will evaluate to true */
2424                 g_truejump (CF_NONE, TrueLab);
2425             }
2426         }
2427
2428         /* Define the false jump label here */
2429         g_defloclabel (lab);
2430
2431         /* Define the label */
2432         lval->e_flags = E_MEXPR;
2433         lval->e_test |= E_CC;   /* Condition codes are set */
2434         k = 0;
2435     }
2436     return k;
2437 }
2438
2439
2440
2441 static int hieOr (struct expent *lval)
2442 /* Process "exp || exp". */
2443 {
2444     int k;
2445     struct expent lval2;
2446     int BoolOp = 0;             /* Did we have a boolean op? */
2447     int AndOp;                  /* Did we have a && operation? */
2448     unsigned TrueLab;           /* Jump to this label if true */
2449     unsigned DoneLab;
2450
2451     /* Get a label */
2452     TrueLab = GetLabel ();
2453
2454     /* Call the next level parser */
2455     k = hieAnd (lval, TrueLab, &BoolOp);
2456
2457     /* Any boolean or's? */
2458     if (curtok == TOK_BOOL_OR) {
2459
2460         /* If the expr hasn't set condition codes, set the force-test flag */
2461         if ((lval->e_test & E_CC) == 0) {
2462             lval->e_test |= E_FORCETEST;
2463         }
2464
2465         /* Get first expr */
2466         exprhs (CF_FORCECHAR, k, lval);
2467
2468         /* For each expression jump to TrueLab if true. Beware: If we
2469          * had && operators, the jump is already in place!
2470          */
2471         if (!BoolOp) {
2472             g_truejump (CF_NONE, TrueLab);
2473         }
2474
2475         /* Remember that we had a boolean op */
2476         BoolOp = 1;
2477
2478         /* while there's more expr */
2479         while (curtok == TOK_BOOL_OR) {
2480
2481             /* skip the || */
2482             NextToken ();
2483
2484             /* Get a subexpr */
2485             AndOp = 0;
2486             k = hieAnd (&lval2, TrueLab, &AndOp);
2487             if ((lval2.e_test & E_CC) == 0) {
2488                 lval2.e_test |= E_FORCETEST;
2489             }
2490             exprhs (CF_FORCECHAR, k, &lval2);
2491
2492             /* If there is more to come, add shortcut boolean eval.
2493              * Beware: If we had && operators, the jump is already
2494              * in place!
2495              */
2496 #if     0
2497 /* Seems this sometimes generates wrong code */
2498             if (curtok == TOK_BOOL_OR && !AndOp) {
2499                 g_truejump (CF_NONE, TrueLab);
2500             }
2501 #else
2502             g_truejump (CF_NONE, TrueLab);
2503 #endif
2504         }
2505         lval->e_flags = E_MEXPR;
2506         lval->e_test |= E_CC;                   /* Condition codes are set */
2507         k = 0;
2508     }
2509
2510     /* If we really had boolean ops, generate the end sequence */
2511     if (BoolOp) {
2512         DoneLab = GetLabel ();
2513         g_getimmed (CF_INT | CF_CONST, 0, 0);   /* Load FALSE */
2514         g_falsejump (CF_NONE, DoneLab);
2515         g_defloclabel (TrueLab);
2516         g_getimmed (CF_INT | CF_CONST, 1, 0);   /* Load TRUE */
2517         g_defloclabel (DoneLab);
2518     }
2519     return k;
2520 }
2521
2522
2523
2524 static int hieQuest (struct expent *lval)
2525 /* Parse "lvalue ? exp : exp" */
2526 {
2527     int k;
2528     int labf;
2529     int labt;
2530     struct expent lval2;        /* Expression 2 */
2531     struct expent lval3;        /* Expression 3 */
2532     type* type2;                /* Type of expression 2 */
2533     type* type3;                /* Type of expression 3 */
2534     type* rtype;                /* Type of result */
2535     CodeMark Mark1;             /* Save position in output code */
2536     CodeMark Mark2;             /* Save position in output code */
2537
2538
2539
2540     k = hieOr (lval);
2541     if (curtok == TOK_QUEST) {
2542         NextToken ();
2543         if ((lval->e_test & E_CC) == 0) {
2544             /* Condition codes not set, force a test */
2545             lval->e_test |= E_FORCETEST;
2546         }
2547         exprhs (CF_NONE, k, lval);
2548         labf = GetLabel ();
2549         g_falsejump (CF_NONE, labf);
2550
2551         /* Parse second and third expression */
2552         expression1 (&lval2);
2553         labt = GetLabel ();
2554         ConsumeColon ();
2555         g_jump (labt);
2556         g_defloclabel (labf);
2557         expression1 (&lval3);
2558
2559         /* Check if any conversions are needed, if so, do them.
2560          * Conversion rules for ?: expression are:
2561          *   - if both expressions are int expressions, default promotion
2562          *     rules for ints apply.
2563          *   - if both expressions are pointers of the same type, the
2564          *     result of the expression is of this type.
2565          *   - if one of the expressions is a pointer and the other is
2566          *     a zero constant, the resulting type is that of the pointer
2567          *     type.
2568          *   - all other cases are flagged by an error.
2569          */
2570         type2 = lval2.e_tptr;
2571         type3 = lval3.e_tptr;
2572         if (IsClassInt (type2) && IsClassInt (type3)) {
2573
2574             /* Get common type */
2575             rtype = promoteint (type2, type3);
2576
2577             /* Convert the third expression to this type if needed */
2578             g_typecast (TypeOf (rtype), TypeOf (type3));
2579
2580             /* Setup a new label so that the expr3 code will jump around
2581              * the type cast code for expr2.
2582              */
2583             labf = GetLabel ();         /* Get new label */
2584             Mark1 = GetCodePos ();      /* Remember current position */
2585             g_jump (labf);              /* Jump around code */
2586
2587             /* The jump for expr2 goes here */
2588             g_defloclabel (labt);
2589
2590             /* Create the typecast code for expr2 */
2591             Mark2 = GetCodePos ();      /* Remember position */
2592             g_typecast (TypeOf (rtype), TypeOf (type2));
2593
2594             /* If the typecast did not produce code, remove the jump,
2595              * otherwise output the label.
2596              */
2597             if (GetCodePos() == Mark2) {
2598                 RemoveCode (Mark1);     /* Remove code */
2599             } else {
2600                 /* We have typecast code, output label */
2601                 g_defloclabel (labf);
2602                 labt = 0;               /* Mark other label as invalid */
2603             }
2604
2605         } else if (IsClassPtr (type2) && IsClassPtr (type3)) {
2606             /* Must point to same type */
2607             if (TypeCmp (Indirect (type2), Indirect (type3)) < TC_EQUAL) {
2608                 Error ("Incompatible pointer types");
2609             }
2610             /* Result has the common type */
2611             rtype = lval2.e_tptr;
2612         } else if (IsClassPtr (type2) && IsNullPtr (&lval3)) {
2613             /* Result type is pointer, no cast needed */
2614             rtype = lval2.e_tptr;
2615         } else if (IsNullPtr (&lval2) && IsClassPtr (type3)) {
2616             /* Result type is pointer, no cast needed */
2617             rtype = lval3.e_tptr;
2618         } else {
2619             Error ("Incompatible types");
2620             rtype = lval2.e_tptr;               /* Doesn't matter here */
2621         }
2622
2623         /* If we don't have the label defined until now, do it */
2624         if (labt) {
2625             g_defloclabel (labt);
2626         }
2627
2628         /* Setup the target expression */
2629         lval->e_flags = E_MEXPR;
2630         lval->e_tptr = rtype;
2631         k = 0;
2632     }
2633     return k;
2634 }
2635
2636
2637
2638 static void opeq (GenDesc* Gen, struct expent *lval, int k)
2639 /* Process "op=" operators. */
2640 {
2641     struct expent lval2;
2642     unsigned flags;
2643     CodeMark Mark;
2644     int MustScale;
2645
2646     NextToken ();
2647     if (k == 0) {
2648         Error ("Invalid lvalue in assignment");
2649         return;
2650     }
2651
2652     /* Determine the type of the lhs */
2653     flags = TypeOf (lval->e_tptr);
2654     MustScale = (Gen->Func == g_add || Gen->Func == g_sub) &&
2655                 lval->e_tptr [0] == T_PTR;
2656
2657     /* Get the lhs address on stack (if needed) */
2658     PushAddr (lval);
2659
2660     /* Fetch the lhs into the primary register if needed */
2661     exprhs (CF_NONE, k, lval);
2662
2663     /* Bring the lhs on stack */
2664     Mark = GetCodePos ();
2665     g_push (flags, 0);
2666
2667     /* Evaluate the rhs */
2668     if (evalexpr (CF_NONE, hie1, &lval2) == 0) {
2669         /* The resulting value is a constant. If the generator has the NOPUSH
2670          * flag set, don't push the lhs.
2671          */
2672         if (Gen->Flags & GEN_NOPUSH) {
2673             RemoveCode (Mark);
2674             pop (flags);
2675         }
2676         if (MustScale) {
2677             /* lhs is a pointer, scale rhs */
2678             lval2.e_const *= SizeOf (lval->e_tptr+1);
2679         }
2680
2681         /* If the lhs is character sized, the operation may be later done
2682          * with characters.
2683          */
2684         if (SizeOf (lval->e_tptr) == 1) {
2685             flags |= CF_FORCECHAR;
2686         }
2687
2688         /* Special handling for add and sub - some sort of a hack, but short code */
2689         if (Gen->Func == g_add) {
2690             g_inc (flags | CF_CONST, lval2.e_const);
2691         } else if (Gen->Func == g_sub) {
2692             g_dec (flags | CF_CONST, lval2.e_const);
2693         } else {
2694             Gen->Func (flags | CF_CONST, lval2.e_const);
2695         }
2696     } else {
2697         /* rhs is not constant and already in the primary register */
2698         if (MustScale) {
2699             /* lhs is a pointer, scale rhs */
2700             g_scale (TypeOf (lval2.e_tptr), SizeOf (lval->e_tptr+1));
2701         }
2702
2703         /* If the lhs is character sized, the operation may be later done
2704          * with characters.
2705          */
2706         if (SizeOf (lval->e_tptr) == 1) {
2707             flags |= CF_FORCECHAR;
2708         }
2709
2710         /* Adjust the types of the operands if needed */
2711         Gen->Func (g_typeadjust (flags, TypeOf (lval2.e_tptr)), 0);
2712     }
2713     store (lval);
2714     lval->e_flags = E_MEXPR;
2715 }
2716
2717
2718
2719 static void addsubeq (GenDesc* Gen, struct expent *lval, int k)
2720 /* Process the += and -= operators */
2721 {
2722     struct expent lval2;
2723     unsigned flags;
2724     int MustScale;
2725
2726
2727     if (k == 0) {
2728         Error ("Invalid lvalue in assignment");
2729         return;
2730     }
2731
2732
2733     /* We're currently only able to handle some adressing modes */
2734     if ((lval->e_flags & E_MGLOBAL) == 0 &&     /* Global address? */
2735         (lval->e_flags & E_MLOCAL) == 0  &&     /* Local address? */
2736         (lval->e_flags & E_MCONST) == 0) {      /* Constant address? */
2737         /* Use generic routine */
2738         opeq (Gen, lval, k);
2739         return;
2740     }
2741
2742     /* Skip the operator */
2743     NextToken ();
2744
2745     /* Check if we have a pointer expression and must scale rhs */
2746     MustScale = (lval->e_tptr [0] == T_PTR);
2747
2748     /* Determine the code generator flags */
2749     flags = TypeOf (lval->e_tptr) | CF_FORCECHAR;
2750
2751     /* Evaluate the rhs */
2752     if (evalexpr (CF_NONE, hie1, &lval2) == 0) {
2753         /* The resulting value is a constant. */
2754         if (MustScale) {
2755             /* lhs is a pointer, scale rhs */
2756             lval2.e_const *= SizeOf (lval->e_tptr+1);
2757         }
2758         flags |= CF_CONST;
2759     } else {
2760         /* rhs is not constant and already in the primary register */
2761         if (MustScale) {
2762             /* lhs is a pointer, scale rhs */
2763             g_scale (TypeOf (lval2.e_tptr), SizeOf (lval->e_tptr+1));
2764         }
2765     }
2766
2767     /* Adjust the rhs to the lhs */
2768     g_typeadjust (flags, TypeOf (lval2.e_tptr));
2769
2770     /* Output apropriate code */
2771     if (lval->e_flags & E_MGLOBAL) {
2772         /* Static variable */
2773         flags |= GlobalModeFlags (lval->e_flags);
2774         if (Gen->Tok == TOK_PLUS_ASSIGN) {
2775             g_addeqstatic (flags, lval->e_name, lval->e_const, lval2.e_const);
2776         } else {
2777             g_subeqstatic (flags, lval->e_name, lval->e_const, lval2.e_const);
2778         }
2779     } else if (lval->e_flags & E_MLOCAL) {
2780         /* ref to localvar */
2781         if (Gen->Tok == TOK_PLUS_ASSIGN) {
2782             g_addeqlocal (flags, lval->e_const, lval2.e_const);
2783         } else {
2784             g_subeqlocal (flags, lval->e_const, lval2.e_const);
2785         }
2786     } else if (lval->e_flags & E_MCONST) {
2787         /* ref to absolute address */
2788         flags |= CF_ABSOLUTE;
2789         if (Gen->Tok == TOK_PLUS_ASSIGN) {
2790             g_addeqstatic (flags, lval->e_const, 0, lval2.e_const);
2791         } else {
2792             g_subeqstatic (flags, lval->e_const, 0, lval2.e_const);
2793         }
2794     } else if (lval->e_flags & E_MEXPR) {
2795         /* Address in a/x. */
2796         if (Gen->Tok == TOK_PLUS_ASSIGN) {
2797             g_addeqind (flags, lval->e_const, lval2.e_const);
2798         } else {
2799             g_subeqind (flags, lval->e_const, lval2.e_const);
2800         }
2801     } else {
2802         Internal ("Invalid addressing mode");
2803     }
2804
2805     /* Expression is in the primary now */
2806     lval->e_flags = E_MEXPR;
2807 }
2808
2809
2810
2811 static void Assignment (struct expent* lval)
2812 /* Parse an assignment */
2813 {
2814     int k;
2815     struct expent lval2;
2816     unsigned flags;
2817     type* ltype = lval->e_tptr;
2818
2819     /* Check for assignment to const */
2820     if (IsQualConst (ltype)) {
2821         Error ("Assignment to const");
2822     }
2823
2824     /* cc65 does not have full support for handling structs by value. Since
2825      * assigning structs is one of the more useful operations from this
2826      * familiy, allow it here.
2827      */
2828     if (IsClassStruct (ltype)) {
2829
2830         /* Bring the address of the lhs into the primary and push it */
2831         exprhs (0, 0, lval);
2832         g_push (CF_PTR | CF_UNSIGNED, 0);
2833
2834         /* Get the expression on the right of the '=' into the primary */
2835         k = hie1 (&lval2);
2836         if (k) {
2837             /* Get the address */
2838             exprhs (0, 0, &lval2);
2839         } else {
2840             /* We need an lvalue */
2841             Error ("Invalid lvalue in assignment");
2842         }
2843
2844         /* Push the address (or whatever is in ax in case of errors) */
2845         g_push (CF_PTR | CF_UNSIGNED, 0);
2846
2847         /* Check for equality of the structs */
2848         if (TypeCmp (ltype, lval2.e_tptr) < TC_EQUAL) {
2849             Error ("Incompatible types");
2850         }
2851
2852         /* Load the size of the struct into the primary */
2853         g_getimmed (CF_INT | CF_UNSIGNED | CF_CONST, SizeOf (ltype), 0);
2854
2855         /* Call the memcpy function */
2856         g_call (CF_FIXARGC, "memcpy", 4);
2857
2858     } else {
2859
2860         /* Get the address on stack if needed */
2861         PushAddr (lval);
2862
2863         /* No struct, setup flags for the load */
2864         flags = SizeOf (ltype) == 1? CF_FORCECHAR : CF_NONE;
2865
2866         /* Get the expression on the right of the '=' into the primary */
2867         if (evalexpr (flags, hie1, &lval2) == 0) {
2868             /* Constant expression. Adjust the types */
2869             assignadjust (ltype, &lval2);
2870             /* Put the value into the primary register */
2871             lconst (flags, &lval2);
2872         } else {
2873             /* Expression is not constant and already in the primary */
2874             assignadjust (ltype, &lval2);
2875         }
2876
2877         /* Generate a store instruction */
2878         store (lval);
2879
2880     }
2881
2882     /* Value is still in primary */
2883     lval->e_flags = E_MEXPR;
2884 }
2885
2886
2887
2888 int hie1 (struct expent* lval)
2889 /* Parse first level of expression hierarchy. */
2890 {
2891     int k;
2892
2893     k = hieQuest (lval);
2894     switch (curtok) {
2895
2896         case TOK_RPAREN:
2897         case TOK_SEMI:
2898             return k;
2899
2900         case TOK_ASSIGN:
2901             NextToken ();
2902             if (k == 0) {
2903                 Error ("Invalid lvalue in assignment");
2904             } else {
2905                 Assignment (lval);
2906             }
2907             break;
2908
2909         case TOK_PLUS_ASSIGN:
2910             addsubeq (&GenPASGN, lval, k);
2911             break;
2912
2913         case TOK_MINUS_ASSIGN:
2914             addsubeq (&GenSASGN, lval, k);
2915             break;
2916
2917         case TOK_MUL_ASSIGN:
2918             opeq (&GenMASGN, lval, k);
2919             break;
2920
2921         case TOK_DIV_ASSIGN:
2922             opeq (&GenDASGN, lval, k);
2923             break;
2924
2925         case TOK_MOD_ASSIGN:
2926             opeq (&GenMOASGN, lval, k);
2927             break;
2928
2929         case TOK_SHL_ASSIGN:
2930             opeq (&GenSLASGN, lval, k);
2931             break;
2932
2933         case TOK_SHR_ASSIGN:
2934             opeq (&GenSRASGN, lval, k);
2935             break;
2936
2937         case TOK_AND_ASSIGN:
2938             opeq (&GenAASGN, lval, k);
2939             break;
2940
2941         case TOK_XOR_ASSIGN:
2942             opeq (&GenXOASGN, lval, k);
2943             break;
2944
2945         case TOK_OR_ASSIGN:
2946             opeq (&GenOASGN, lval, k);
2947             break;
2948
2949         default:
2950             return k;
2951     }
2952     return 0;
2953 }
2954
2955
2956
2957 int hie0 (struct expent *lval)
2958 /* Parse comma operator. */
2959 {
2960     int k;
2961
2962     k = hie1 (lval);
2963     while (curtok == TOK_COMMA) {
2964         NextToken ();
2965         k = hie1 (lval);
2966     }
2967     return k;
2968 }
2969
2970
2971
2972 int evalexpr (unsigned flags, int (*f) (struct expent*), struct expent* lval)
2973 /* Will evaluate an expression via the given function. If the result is a
2974  * constant, 0 is returned and the value is put in the lval struct. If the
2975  * result is not constant, exprhs is called to bring the value into the
2976  * primary register and 1 is returned.
2977  */
2978 {
2979     int k;
2980
2981     /* Evaluate */
2982     k = f (lval);
2983     if (k == 0 && lval->e_flags == E_MCONST) {
2984         /* Constant expression */
2985         return 0;
2986     } else {
2987         /* Not constant, load into the primary */
2988         exprhs (flags, k, lval);
2989         return 1;
2990     }
2991 }
2992
2993
2994
2995 int expr (int (*func) (struct expent*), struct expent *lval)
2996 /* Expression parser; func is either hie0 or hie1. */
2997 {
2998     int k;
2999     int savsp;
3000
3001     savsp = oursp;
3002
3003     k = (*func) (lval);
3004
3005     /* Do some checks if code generation is still constistent */
3006     if (savsp != oursp) {
3007         if (Debug) {
3008             fprintf (stderr, "oursp != savesp (%d != %d)\n", oursp, savsp);
3009         } else {
3010             Internal ("oursp != savsp (%d != %d)", oursp, savsp);
3011         }
3012     }
3013     return k;
3014 }
3015
3016
3017
3018 void expression1 (struct expent* lval)
3019 /* Evaluate an expression on level 1 (no comma operator) and put it into
3020  * the primary register
3021  */
3022 {
3023     memset (lval, 0, sizeof (*lval));
3024     exprhs (CF_NONE, expr (hie1, lval), lval);
3025 }
3026
3027
3028
3029 void expression (struct expent* lval)
3030 /* Evaluate an expression and put it into the primary register */
3031 {
3032     memset (lval, 0, sizeof (*lval));
3033     exprhs (CF_NONE, expr (hie0, lval), lval);
3034 }
3035
3036
3037
3038 void constexpr (struct expent* lval)
3039 /* Get a constant value */
3040 {
3041     memset (lval, 0, sizeof (*lval));
3042     if (expr (hie1, lval) != 0 || (lval->e_flags & E_MCONST) == 0) {
3043         Error ("Constant expression expected");
3044         /* To avoid any compiler errors, make the expression a valid const */
3045         lval->e_flags = E_MCONST;
3046         lval->e_tptr = type_int;
3047         lval->e_const = 0;
3048     }
3049 }
3050
3051
3052
3053 void intexpr (struct expent* lval)
3054 /* Get an integer expression */
3055 {
3056     expression (lval);
3057     if (!IsClassInt (lval->e_tptr)) {
3058         Error ("Integer expression expected");
3059         /* To avoid any compiler errors, make the expression a valid int */
3060         lval->e_flags = E_MCONST;
3061         lval->e_tptr = type_int;
3062         lval->e_const = 0;
3063     }
3064 }
3065
3066
3067
3068 void boolexpr (struct expent* lval)
3069 /* Get a boolean expression */
3070 {
3071     /* Read an expression */
3072     expression (lval);
3073
3074     /* If it's an integer, it's ok. If it's not an integer, but a pointer,
3075      * the pointer used in a boolean context is also ok
3076      */
3077     if (!IsClassInt (lval->e_tptr) && !IsClassPtr (lval->e_tptr)) {
3078         Error ("Boolean expression expected");
3079         /* To avoid any compiler errors, make the expression a valid int */
3080         lval->e_flags = E_MCONST;
3081         lval->e_tptr = type_int;
3082         lval->e_const = 0;
3083     }
3084 }
3085
3086
3087
3088 void test (unsigned label, int cond)
3089 /* Generate code to perform test and jump if false. */
3090 {
3091     int k;
3092     struct expent lval;
3093
3094     /* Eat the parenthesis */
3095     ConsumeLParen ();
3096
3097     /* Prepare the expression, setup labels */
3098     memset (&lval, 0, sizeof (lval));
3099
3100     /* Generate code to eval the expr */
3101     k = expr (hie0, &lval);
3102     if (k == 0 && lval.e_flags == E_MCONST) {
3103         /* Constant rvalue */
3104         if (cond == 0 && lval.e_const == 0) {
3105             g_jump (label);
3106             Warning ("Unreachable code");
3107         } else if (cond && lval.e_const) {
3108             g_jump (label);
3109         }
3110         ConsumeRParen ();
3111         return;
3112     }
3113
3114     /* If the expr hasn't set condition codes, set the force-test flag */
3115     if ((lval.e_test & E_CC) == 0) {
3116         lval.e_test |= E_FORCETEST;
3117     }
3118
3119     /* Load the value into the primary register */
3120     exprhs (CF_FORCECHAR, k, &lval);
3121
3122     /* Check for the closing brace */
3123     ConsumeRParen ();
3124
3125     /* Generate the jump */
3126     if (cond) {
3127         g_truejump (CF_NONE, label);
3128     } else {
3129         /* Special case (putting this here is a small hack - but hey, the
3130          * compiler itself is one big hack...): If a semicolon follows, we
3131          * don't have a statement and may omit the jump.
3132          */
3133         if (curtok != TOK_SEMI) {
3134             g_falsejump (CF_NONE, label);
3135         }
3136     }
3137 }
3138
3139
3140
3141