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