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