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