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