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