]> git.sur5r.net Git - cc65/blob - src/cc65/expr.c
f35f6a9d3f6df94120fe13a60c3c68576843d863
[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                 /* IDENT is either an auto-declared function or an undefined variable. */
733                 if (CurTok.Tok == TOK_LPAREN) {
734                     /* Declare a function returning int. For that purpose, prepare a
735                      * function signature for a function having an empty param list
736                      * and returning int.
737                      */
738                     Warning ("Function call without a prototype");
739                     Sym = AddGlobalSym (Ident, GetImplicitFuncType(), SC_EXTERN | SC_REF | SC_FUNC);
740                     E->Type  = Sym->Type;
741                     E->Flags = E_LOC_GLOBAL | E_RTYPE_RVAL;
742                     E->Name  = (unsigned long) Sym->Name;
743                 } else {
744                     /* Undeclared Variable */
745                     Sym = AddLocalSym (Ident, type_int, SC_AUTO | SC_REF, 0);
746                     E->Flags = E_LOC_STACK | E_RTYPE_LVAL;
747                     E->Type = type_int;
748                     Error ("Undefined symbol: `%s'", Ident);
749                 }
750
751             }
752             break;
753
754         case TOK_SCONST:
755             /* String literal */
756             E->Type  = GetCharArrayType (GetLiteralPoolOffs () - CurTok.IVal);
757             E->Flags = E_LOC_LITERAL | E_RTYPE_RVAL;
758             E->IVal  = CurTok.IVal;
759             E->Name  = LiteralPoolLabel;
760             NextToken ();
761             break;
762
763         case TOK_ASM:
764             /* ASM statement */
765             AsmStatement ();
766             E->Flags = E_LOC_EXPR | E_RTYPE_RVAL;
767             E->Type  = type_void;
768             break;
769
770         case TOK_A:
771             /* Register pseudo variable */
772             E->Type  = type_uchar;
773             E->Flags = E_LOC_PRIMARY | E_RTYPE_LVAL;
774             NextToken ();
775             break;
776
777         case TOK_AX:
778             /* Register pseudo variable */
779             E->Type  = type_uint;
780             E->Flags = E_LOC_PRIMARY | E_RTYPE_LVAL;
781             NextToken ();
782             break;
783
784         case TOK_EAX:
785             /* Register pseudo variable */
786             E->Type  = type_ulong;
787             E->Flags = E_LOC_PRIMARY | E_RTYPE_LVAL;
788             NextToken ();
789             break;
790
791         default:
792             /* Illegal primary. */
793             Error ("Expression expected");
794             ED_MakeConstAbsInt (E, 1);
795             break;
796     }
797 }
798
799
800
801 static void ArrayRef (ExprDesc* Expr)
802 /* Handle an array reference. This function needs a rewrite. */
803 {
804     int         ConstBaseAddr;
805     ExprDesc    SubScript;
806     CodeMark    Mark1;
807     CodeMark    Mark2;
808     Type*       ElementType;
809     Type*       tptr1;
810
811
812     /* Skip the bracket */
813     NextToken ();
814
815     /* Get the type of left side */
816     tptr1 = Expr->Type;
817
818     /* We can apply a special treatment for arrays that have a const base
819      * address. This is true for most arrays and will produce a lot better
820      * code. Check if this is a const base address.
821      */
822     ConstBaseAddr = ED_IsRVal (Expr) &&
823                     (ED_IsLocConst (Expr) || ED_IsLocStack (Expr));
824
825     /* If we have a constant base, we delay the address fetch */
826     GetCodePos (&Mark1);
827     if (!ConstBaseAddr) {
828         /* Get a pointer to the array into the primary */
829         LoadExpr (CF_NONE, Expr);
830
831         /* Get the array pointer on stack. Do not push more than 16
832          * bit, even if this value is greater, since we cannot handle
833          * other than 16bit stuff when doing indexing.
834          */
835         GetCodePos (&Mark2);
836         g_push (CF_PTR, 0);
837     }
838
839     /* TOS now contains ptr to array elements. Get the subscript. */
840     ExprWithCheck (hie0, &SubScript);
841
842     /* Check the types of array and subscript. We can either have a
843      * pointer/array to the left, in which case the subscript must be of an
844      * integer type, or we have an integer to the left, in which case the
845      * subscript must be a pointer/array.
846      * Since we do the necessary checking here, we can rely later on the
847      * correct types.
848      */
849     if (IsClassPtr (Expr->Type)) {
850         if (!IsClassInt (SubScript.Type))  {
851             Error ("Array subscript is not an integer");
852             /* To avoid any compiler errors, make the expression a valid int */
853             ED_MakeConstAbsInt (&SubScript, 0);
854         }
855         ElementType = Indirect (Expr->Type);
856     } else if (IsClassInt (Expr->Type)) {
857         if (!IsClassPtr (SubScript.Type)) {
858             Error ("Subscripted value is neither array nor pointer");
859             /* To avoid compiler errors, make the subscript a char[] at
860              * address 0.
861              */
862             ED_MakeConstAbs (&SubScript, 0, GetCharArrayType (1));
863         }
864         ElementType = Indirect (SubScript.Type);
865     } else {
866         Error ("Cannot subscript");
867         /* To avoid compiler errors, fake both the array and the subscript, so
868          * we can just proceed.
869          */
870         ED_MakeConstAbs (Expr, 0, GetCharArrayType (1));
871         ED_MakeConstAbsInt (&SubScript, 0);
872         ElementType = Indirect (Expr->Type);
873     }
874
875     /* Check if the subscript is constant absolute value */
876     if (ED_IsConstAbs (&SubScript)) {
877
878         /* The array subscript is a numeric constant. If we had pushed the
879          * array base address onto the stack before, we can remove this value,
880          * since we can generate expression+offset.
881          */
882         if (!ConstBaseAddr) {
883             RemoveCode (&Mark2);
884         } else {
885             /* Get an array pointer into the primary */
886             LoadExpr (CF_NONE, Expr);
887         }
888
889         if (IsClassPtr (Expr->Type)) {
890
891             /* Lhs is pointer/array. Scale the subscript value according to
892              * the element size.
893              */
894             SubScript.IVal *= CheckedSizeOf (ElementType);
895
896             /* Remove the address load code */
897             RemoveCode (&Mark1);
898
899             /* In case of an array, we can adjust the offset of the expression
900              * already in Expr. If the base address was a constant, we can even
901              * remove the code that loaded the address into the primary.
902              */
903             if (IsTypeArray (Expr->Type)) {
904
905                 /* Adjust the offset */
906                 Expr->IVal += SubScript.IVal;
907
908             } else {
909
910                 /* It's a pointer, so we do have to load it into the primary
911                  * first (if it's not already there).
912                  */
913                 if (ConstBaseAddr || ED_IsLVal (Expr)) {
914                     LoadExpr (CF_NONE, Expr);
915                     ED_MakeRValExpr (Expr);
916                 }
917
918                 /* Use the offset */
919                 Expr->IVal = SubScript.IVal;
920             }
921
922         } else {
923
924             /* Scale the rhs value according to the element type */
925             g_scale (TypeOf (tptr1), CheckedSizeOf (ElementType));
926
927             /* Add the subscript. Since arrays are indexed by integers,
928              * we will ignore the true type of the subscript here and
929              * use always an int. #### Use offset but beware of LoadExpr!
930              */
931             g_inc (CF_INT | CF_CONST, SubScript.IVal);
932
933         }
934
935     } else {
936
937         /* Array subscript is not constant. Load it into the primary */
938         GetCodePos (&Mark2);
939         LoadExpr (CF_NONE, &SubScript);
940
941         /* Do scaling */
942         if (IsClassPtr (Expr->Type)) {
943
944             /* Indexing is based on unsigneds, so we will just use the integer
945              * portion of the index (which is in (e)ax, so there's no further
946              * action required).
947              */
948             g_scale (CF_INT, CheckedSizeOf (ElementType));
949
950         } else {
951
952             /* Get the int value on top. If we come here, we're sure, both
953              * values are 16 bit (the first one was truncated if necessary
954              * and the second one is a pointer). Note: If ConstBaseAddr is
955              * true, we don't have a value on stack, so to "swap" both, just
956              * push the subscript.
957              */
958             if (ConstBaseAddr) {
959                 g_push (CF_INT, 0);
960                 LoadExpr (CF_NONE, Expr);
961                 ConstBaseAddr = 0;
962             } else {
963                 g_swap (CF_INT);
964             }
965
966             /* Scale it */
967             g_scale (TypeOf (tptr1), CheckedSizeOf (ElementType));
968
969         }
970
971         /* The offset is now in the primary register. It we didn't have a
972          * constant base address for the lhs, the lhs address is already
973          * on stack, and we must add the offset. If the base address was
974          * constant, we call special functions to add the address to the
975          * offset value.
976          */
977         if (!ConstBaseAddr) {
978
979             /* The array base address is on stack and the subscript is in the
980              * primary. Add both.
981              */
982             g_add (CF_INT, 0);
983
984         } else {
985
986             /* The subscript is in the primary, and the array base address is
987              * in Expr. If the subscript has itself a constant address, it is
988              * often a better idea to reverse again the order of the
989              * evaluation. This will generate better code if the subscript is
990              * a byte sized variable. But beware: This is only possible if the
991              * subscript was not scaled, that is, if this was a byte array
992              * or pointer.
993              */
994             if ((ED_IsLocConst (&SubScript) || ED_IsLocStack (&SubScript)) &&
995                 CheckedSizeOf (ElementType) == SIZEOF_CHAR) {
996
997                 unsigned Flags;
998
999                 /* Reverse the order of evaluation */
1000                 if (CheckedSizeOf (SubScript.Type) == SIZEOF_CHAR) {
1001                     Flags = CF_CHAR;
1002                 } else {
1003                     Flags = CF_INT;
1004                 }
1005                 RemoveCode (&Mark2);
1006
1007                 /* Get a pointer to the array into the primary. */
1008                 LoadExpr (CF_NONE, Expr);
1009
1010                 /* Add the variable */
1011                 if (ED_IsLocStack (&SubScript)) {
1012                     g_addlocal (Flags, SubScript.IVal);
1013                 } else {
1014                     Flags |= GlobalModeFlags (SubScript.Flags);
1015                     g_addstatic (Flags, SubScript.Name, SubScript.IVal);
1016                 }
1017             } else {
1018                 if (ED_IsLocAbs (Expr)) {
1019                     /* Constant numeric address. Just add it */
1020                     g_inc (CF_INT, Expr->IVal);
1021                 } else if (ED_IsLocStack (Expr)) {
1022                     /* Base address is a local variable address */
1023                     if (IsTypeArray (Expr->Type)) {
1024                         g_addaddr_local (CF_INT, Expr->IVal);
1025                     } else {
1026                         g_addlocal (CF_PTR, Expr->IVal);
1027                     }
1028                 } else {
1029                     /* Base address is a static variable address */
1030                     unsigned Flags = CF_INT | GlobalModeFlags (Expr->Flags);
1031                     if (IsTypeArray (Expr->Type)) {
1032                         g_addaddr_static (Flags, Expr->Name, Expr->IVal);
1033                     } else {
1034                         g_addstatic (Flags, Expr->Name, Expr->IVal);
1035                     }
1036                 }
1037             }
1038
1039
1040         }
1041
1042         /* The result is an expression in the primary */
1043         ED_MakeRValExpr (Expr);
1044
1045     }
1046
1047     /* Result is of element type */
1048     Expr->Type = ElementType;
1049
1050     /* An array element is actually a variable. So the rules for variables
1051      * with respect to the reference type apply: If it's an array, it is
1052      * a rvalue, otherwise it's an lvalue. (A function would also be a rvalue,
1053      * but an array cannot contain functions).
1054      */
1055     if (IsTypeArray (Expr->Type)) {
1056         ED_MakeRVal (Expr);
1057     } else {
1058         ED_MakeLVal (Expr);
1059     }
1060
1061     /* Consume the closing bracket */
1062     ConsumeRBrack ();
1063 }
1064
1065
1066
1067 static void StructRef (ExprDesc* Expr)
1068 /* Process struct field after . or ->. */
1069 {
1070     ident Ident;
1071     SymEntry* Field;
1072
1073     /* Skip the token and check for an identifier */
1074     NextToken ();
1075     if (CurTok.Tok != TOK_IDENT) {
1076         Error ("Identifier expected");
1077         Expr->Type = type_int;
1078         return;
1079     }
1080
1081     /* Get the symbol table entry and check for a struct field */
1082     strcpy (Ident, CurTok.Ident);
1083     NextToken ();
1084     Field = FindStructField (Expr->Type, Ident);
1085     if (Field == 0) {
1086         Error ("Struct/union has no field named `%s'", Ident);
1087         Expr->Type = type_int;
1088         return;
1089     }
1090
1091     /* If we have a struct pointer that is an lvalue and not already in the
1092      * primary, load it now.
1093      */
1094     if (ED_IsLVal (Expr) && IsTypePtr (Expr->Type)) {
1095
1096         /* Load into the primary */
1097         LoadExpr (CF_NONE, Expr);
1098
1099         /* Make it an lvalue expression */
1100         ED_MakeLValExpr (Expr);
1101     }
1102
1103     /* Set the struct field offset */
1104     Expr->IVal += Field->V.Offs;
1105
1106     /* The type is now the type of the field */
1107     Expr->Type = Field->Type;
1108
1109     /* An struct member is actually a variable. So the rules for variables
1110      * with respect to the reference type apply: If it's an array, it is
1111      * a rvalue, otherwise it's an lvalue. (A function would also be a rvalue,
1112      * but a struct field cannot be a function).
1113      */
1114     if (IsTypeArray (Expr->Type)) {
1115         ED_MakeRVal (Expr);
1116     } else {
1117         ED_MakeLVal (Expr);
1118     }
1119 }
1120
1121
1122
1123 static void hie11 (ExprDesc *Expr)
1124 /* Handle compound types (structs and arrays) */
1125 {
1126     /* Name value used in invalid function calls */
1127     static const char IllegalFunc[] = "illegal_function_call";
1128
1129     /* Evaluate the lhs */
1130     Primary (Expr);
1131
1132     /* Check for a rhs */
1133     while (CurTok.Tok == TOK_LBRACK || CurTok.Tok == TOK_LPAREN ||
1134            CurTok.Tok == TOK_DOT    || CurTok.Tok == TOK_PTR_REF) {
1135
1136         switch (CurTok.Tok) {
1137
1138             case TOK_LBRACK:
1139                 /* Array reference */
1140                 ArrayRef (Expr);
1141                 break;
1142
1143             case TOK_LPAREN:
1144                 /* Function call. */
1145                 if (!IsTypeFunc (Expr->Type) && !IsTypeFuncPtr (Expr->Type)) {
1146                     /* Not a function */
1147                     Error ("Illegal function call");
1148                     /* Force the type to be a implicitly defined function, one
1149                      * returning an int and taking any number of arguments.
1150                      * Since we don't have a name, invent one.
1151                      */
1152                     ED_MakeConstAbs (Expr, 0, GetImplicitFuncType ());
1153                     Expr->Name = (long) IllegalFunc;
1154                 }
1155                 /* Call the function */
1156                 FunctionCall (Expr);
1157                 break;
1158
1159             case TOK_DOT:
1160                 if (!IsClassStruct (Expr->Type)) {
1161                     Error ("Struct expected");
1162                 }
1163                 StructRef (Expr);
1164                 break;
1165
1166             case TOK_PTR_REF:
1167                 /* If we have an array, convert it to pointer to first element */
1168                 if (IsTypeArray (Expr->Type)) {
1169                     Expr->Type = ArrayToPtr (Expr->Type);
1170                 }
1171                 if (!IsClassPtr (Expr->Type) || !IsClassStruct (Indirect (Expr->Type))) {
1172                     Error ("Struct pointer expected");
1173                 }
1174                 StructRef (Expr);
1175                 break;
1176
1177             default:
1178                 Internal ("Invalid token in hie11: %d", CurTok.Tok);
1179
1180         }
1181     }
1182 }
1183
1184
1185
1186 void Store (ExprDesc* Expr, const Type* StoreType)
1187 /* Store the primary register into the location denoted by Expr. If StoreType
1188  * is given, use this type when storing instead of Expr->Type. If StoreType
1189  * is NULL, use Expr->Type instead.
1190  */
1191 {
1192     unsigned Flags;
1193
1194     /* If StoreType was not given, use Expr->Type instead */
1195     if (StoreType == 0) {
1196         StoreType = Expr->Type;
1197     }
1198
1199     /* Prepare the code generator flags */
1200     Flags = TypeOf (StoreType);
1201
1202     /* Do the store depending on the location */
1203     switch (ED_GetLoc (Expr)) {
1204
1205         case E_LOC_ABS:
1206             /* Absolute: numeric address or const */
1207             g_putstatic (Flags | CF_ABSOLUTE, Expr->IVal, 0);
1208             break;
1209
1210         case E_LOC_GLOBAL:
1211             /* Global variable */
1212             g_putstatic (Flags | CF_EXTERNAL, Expr->Name, Expr->IVal);
1213             break;
1214
1215         case E_LOC_STATIC:
1216         case E_LOC_LITERAL:
1217             /* Static variable or literal in the literal pool */
1218             g_putstatic (Flags | CF_STATIC, Expr->Name, Expr->IVal);
1219             break;                 
1220
1221         case E_LOC_REGISTER:
1222             /* Register variable */
1223             g_putstatic (Flags | CF_REGVAR, Expr->Name, Expr->IVal);
1224             break;
1225
1226         case E_LOC_STACK:
1227             /* Value on the stack */
1228             g_putlocal (Flags, Expr->IVal, 0);
1229             break;
1230
1231         case E_LOC_PRIMARY:
1232             /* The primary register (value is already there) */
1233             /* ### Do we need a test here if the flag is set? */
1234             break;
1235
1236         case E_LOC_EXPR:
1237             /* An expression in the primary register */
1238             g_putind (Flags, Expr->IVal);
1239             break;
1240
1241         default:
1242             Internal ("Invalid location in Store(): 0x%04X", ED_GetLoc (Expr));
1243     }
1244
1245     /* Assume that each one of the stores will invalidate CC */
1246     ED_MarkAsUntested (Expr);
1247 }
1248
1249
1250
1251 static void PreInc (ExprDesc* Expr)
1252 /* Handle the preincrement operators */
1253 {
1254     unsigned Flags;
1255     unsigned long Val;
1256
1257     /* Skip the operator token */
1258     NextToken ();
1259
1260     /* Evaluate the expression and check that it is an lvalue */
1261     hie10 (Expr);
1262     if (!ED_IsLVal (Expr)) {
1263         Error ("Invalid lvalue");
1264         return;
1265     }
1266
1267     /* Get the data type */
1268     Flags = TypeOf (Expr->Type) | CF_FORCECHAR | CF_CONST;
1269
1270     /* Get the increment value in bytes */
1271     Val = IsTypePtr (Expr->Type)? CheckedPSizeOf (Expr->Type) : 1;
1272
1273     /* Check the location of the data */
1274     switch (ED_GetLoc (Expr)) {
1275
1276         case E_LOC_ABS:
1277             /* Absolute: numeric address or const */
1278             g_addeqstatic (Flags | CF_ABSOLUTE, Expr->IVal, 0, Val);
1279             break;
1280
1281         case E_LOC_GLOBAL:
1282             /* Global variable */
1283             g_addeqstatic (Flags | CF_EXTERNAL, Expr->Name, Expr->IVal, Val);
1284             break;
1285
1286         case E_LOC_STATIC:
1287         case E_LOC_LITERAL:
1288             /* Static variable or literal in the literal pool */
1289             g_addeqstatic (Flags | CF_STATIC, Expr->Name, Expr->IVal, Val);
1290             break;
1291
1292         case E_LOC_REGISTER:
1293             /* Register variable */
1294             g_addeqstatic (Flags | CF_REGVAR, Expr->Name, Expr->IVal, Val);
1295             break;
1296
1297         case E_LOC_STACK:
1298             /* Value on the stack */
1299             g_addeqlocal (Flags, Expr->IVal, Val);
1300             break;
1301
1302         case E_LOC_PRIMARY:
1303             /* The primary register */
1304             g_inc (Flags, Val);
1305             break;
1306
1307         case E_LOC_EXPR:
1308             /* An expression in the primary register */
1309             g_addeqind (Flags, Expr->IVal, Val);
1310             break;
1311
1312         default:
1313             Internal ("Invalid location in PreInc(): 0x%04X", ED_GetLoc (Expr));
1314     }
1315
1316     /* Result is an expression, no reference */
1317     ED_MakeRValExpr (Expr);
1318 }
1319
1320
1321
1322 static void PreDec (ExprDesc* Expr)
1323 /* Handle the predecrement operators */
1324 {
1325     unsigned Flags;
1326     unsigned long Val;
1327
1328     /* Skip the operator token */
1329     NextToken ();
1330
1331     /* Evaluate the expression and check that it is an lvalue */
1332     hie10 (Expr);
1333     if (!ED_IsLVal (Expr)) {
1334         Error ("Invalid lvalue");
1335         return;
1336     }
1337
1338     /* Get the data type */
1339     Flags = TypeOf (Expr->Type) | CF_FORCECHAR | CF_CONST;
1340
1341     /* Get the increment value in bytes */
1342     Val = IsTypePtr (Expr->Type)? CheckedPSizeOf (Expr->Type) : 1;
1343
1344     /* Check the location of the data */
1345     switch (ED_GetLoc (Expr)) {
1346
1347         case E_LOC_ABS:
1348             /* Absolute: numeric address or const */
1349             g_subeqstatic (Flags | CF_ABSOLUTE, Expr->IVal, 0, Val);
1350             break;
1351
1352         case E_LOC_GLOBAL:
1353             /* Global variable */
1354             g_subeqstatic (Flags | CF_EXTERNAL, Expr->Name, Expr->IVal, Val);
1355             break;
1356
1357         case E_LOC_STATIC:
1358         case E_LOC_LITERAL:
1359             /* Static variable or literal in the literal pool */
1360             g_subeqstatic (Flags | CF_STATIC, Expr->Name, Expr->IVal, Val);
1361             break;
1362
1363         case E_LOC_REGISTER:
1364             /* Register variable */
1365             g_subeqstatic (Flags | CF_REGVAR, Expr->Name, Expr->IVal, Val);
1366             break;
1367
1368         case E_LOC_STACK:
1369             /* Value on the stack */
1370             g_subeqlocal (Flags, Expr->IVal, Val);
1371             break;
1372
1373         case E_LOC_PRIMARY:
1374             /* The primary register */
1375             g_inc (Flags, Val);
1376             break;
1377
1378         case E_LOC_EXPR:
1379             /* An expression in the primary register */
1380             g_subeqind (Flags, Expr->IVal, Val);
1381             break;
1382
1383         default:
1384             Internal ("Invalid location in PreDec(): 0x%04X", ED_GetLoc (Expr));
1385     }
1386
1387     /* Result is an expression, no reference */
1388     ED_MakeRValExpr (Expr);
1389 }
1390
1391
1392
1393 static void PostIncDec (ExprDesc* Expr, void (*inc) (unsigned, unsigned long))
1394 /* Handle i-- and i++ */
1395 {
1396     unsigned Flags;
1397
1398     NextToken ();
1399
1400     /* The expression to increment must be an lvalue */
1401     if (!ED_IsLVal (Expr)) {
1402         Error ("Invalid lvalue");
1403         return;
1404     }
1405
1406     /* Get the data type */
1407     Flags = TypeOf (Expr->Type);
1408
1409     /* Push the address if needed */
1410     PushAddr (Expr);
1411
1412     /* Fetch the value and save it (since it's the result of the expression) */
1413     LoadExpr (CF_NONE, Expr);
1414     g_save (Flags | CF_FORCECHAR);
1415
1416     /* If we have a pointer expression, increment by the size of the type */
1417     if (IsTypePtr (Expr->Type)) {
1418         inc (Flags | CF_CONST | CF_FORCECHAR, CheckedSizeOf (Expr->Type + 1));
1419     } else {
1420         inc (Flags | CF_CONST | CF_FORCECHAR, 1);
1421     }
1422
1423     /* Store the result back */
1424     Store (Expr, 0);
1425
1426     /* Restore the original value in the primary register */
1427     g_restore (Flags | CF_FORCECHAR);
1428
1429     /* The result is always an expression, no reference */
1430     ED_MakeRValExpr (Expr);
1431 }
1432
1433
1434
1435 static void UnaryOp (ExprDesc* Expr)
1436 /* Handle unary -/+ and ~ */
1437 {
1438     unsigned Flags;
1439
1440     /* Remember the operator token and skip it */
1441     token_t Tok = CurTok.Tok;
1442     NextToken ();
1443
1444     /* Get the expression */
1445     hie10 (Expr);
1446
1447     /* We can only handle integer types */
1448     if (!IsClassInt (Expr->Type)) {
1449         Error ("Argument must have integer type");
1450         ED_MakeConstAbsInt (Expr, 1);
1451     }
1452
1453     /* Check for a constant expression */
1454     if (ED_IsConstAbs (Expr)) {
1455         /* Value is constant */
1456         switch (Tok) {
1457             case TOK_MINUS: Expr->IVal = -Expr->IVal;   break;
1458             case TOK_PLUS:                              break;
1459             case TOK_COMP:  Expr->IVal = ~Expr->IVal;   break;
1460             default:        Internal ("Unexpected token: %d", Tok);
1461         }
1462     } else {
1463         /* Value is not constant */
1464         LoadExpr (CF_NONE, Expr);
1465
1466         /* Get the type of the expression */
1467         Flags = TypeOf (Expr->Type);
1468
1469         /* Handle the operation */
1470         switch (Tok) {
1471             case TOK_MINUS: g_neg (Flags);  break;
1472             case TOK_PLUS:                  break;
1473             case TOK_COMP:  g_com (Flags);  break;
1474             default:        Internal ("Unexpected token: %d", Tok);
1475         }
1476
1477         /* The result is a rvalue in the primary */
1478         ED_MakeRValExpr (Expr);
1479     }
1480 }
1481
1482
1483
1484 void hie10 (ExprDesc* Expr)
1485 /* Handle ++, --, !, unary - etc. */
1486 {
1487     unsigned long Size;
1488
1489     switch (CurTok.Tok) {
1490
1491         case TOK_INC:
1492             PreInc (Expr);
1493             break;
1494
1495         case TOK_DEC:
1496             PreDec (Expr);
1497             break;
1498
1499         case TOK_PLUS:
1500         case TOK_MINUS:
1501         case TOK_COMP:
1502             UnaryOp (Expr);
1503             break;
1504
1505         case TOK_BOOL_NOT:
1506             NextToken ();
1507             if (evalexpr (CF_NONE, hie10, Expr) == 0) {
1508                 /* Constant expression */
1509                 Expr->IVal = !Expr->IVal;
1510             } else {
1511                 g_bneg (TypeOf (Expr->Type));
1512                 ED_MakeRValExpr (Expr);
1513                 ED_TestDone (Expr);             /* bneg will set cc */
1514             }
1515             break;
1516
1517         case TOK_STAR:
1518             NextToken ();
1519             ExprWithCheck (hie10, Expr);
1520             if (ED_IsLVal (Expr) || !(ED_IsLocConst (Expr) || ED_IsLocStack (Expr))) {
1521                 /* Not a const, load it into the primary and make it a
1522                  * calculated value.
1523                  */
1524                 LoadExpr (CF_NONE, Expr);
1525                 ED_MakeRValExpr (Expr);
1526             }
1527             /* If the expression is already a pointer to function, the
1528              * additional dereferencing operator must be ignored.
1529              */
1530             if (IsTypeFuncPtr (Expr->Type)) {
1531                 /* Expression not storable */
1532                 ED_MakeRVal (Expr);
1533             } else {
1534                 if (IsClassPtr (Expr->Type)) {
1535                     Expr->Type = Indirect (Expr->Type);
1536                 } else {
1537                     Error ("Illegal indirection");
1538                 }
1539                 ED_MakeLVal (Expr);
1540             }
1541             break;
1542
1543         case TOK_AND:
1544             NextToken ();
1545             ExprWithCheck (hie10, Expr);
1546             /* The & operator may be applied to any lvalue, and it may be
1547              * applied to functions, even if they're no lvalues.
1548              */
1549             if (ED_IsRVal (Expr) && !IsTypeFunc (Expr->Type)) {
1550                 /* Allow the & operator with an array */
1551                 if (!IsTypeArray (Expr->Type)) {
1552                     Error ("Illegal address");
1553                 }
1554             } else {
1555                 Expr->Type = PointerTo (Expr->Type);
1556                 ED_MakeRVal (Expr);
1557             }
1558             break;
1559
1560         case TOK_SIZEOF:
1561             NextToken ();
1562             if (TypeSpecAhead ()) {
1563                 Type T[MAXTYPELEN];
1564                 NextToken ();
1565                 Size = CheckedSizeOf (ParseType (T));
1566                 ConsumeRParen ();
1567             } else {
1568                 /* Remember the output queue pointer */
1569                 CodeMark Mark;
1570                 GetCodePos (&Mark);
1571                 hie10 (Expr);
1572                 Size = CheckedSizeOf (Expr->Type);
1573                 /* Remove any generated code */
1574                 RemoveCode (&Mark);
1575             }
1576             ED_MakeConstAbs (Expr, Size, type_size_t);
1577             ED_MarkAsUntested (Expr);
1578             break;
1579
1580         default:
1581             if (TypeSpecAhead ()) {
1582
1583                 /* A typecast */
1584                 TypeCast (Expr);
1585
1586             } else {
1587
1588                 /* An expression */
1589                 hie11 (Expr);
1590
1591                 /* Handle post increment */
1592                 if (CurTok.Tok == TOK_INC) {
1593                     PostIncDec (Expr, g_inc);
1594                 } else if (CurTok.Tok == TOK_DEC) {
1595                     PostIncDec (Expr, g_dec);
1596                 }
1597
1598             }
1599             break;
1600     }
1601 }
1602
1603
1604
1605 static void hie_internal (const GenDesc* Ops,   /* List of generators */
1606                           ExprDesc* Expr,
1607                           void (*hienext) (ExprDesc*),
1608                           int* UsedGen)
1609 /* Helper function */
1610 {
1611     ExprDesc Expr2;
1612     CodeMark Mark1;
1613     CodeMark Mark2;
1614     const GenDesc* Gen;
1615     token_t Tok;                        /* The operator token */
1616     unsigned ltype, type;
1617     int rconst;                         /* Operand is a constant */
1618
1619
1620     hienext (Expr);
1621
1622     *UsedGen = 0;
1623     while ((Gen = FindGen (CurTok.Tok, Ops)) != 0) {
1624
1625         /* Tell the caller that we handled it's ops */
1626         *UsedGen = 1;
1627
1628         /* All operators that call this function expect an int on the lhs */
1629         if (!IsClassInt (Expr->Type)) {
1630             Error ("Integer expression expected");
1631             /* To avoid further errors, make Expr a valid int expression */
1632             ED_MakeConstAbsInt (Expr, 1);
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->C != T_VOID && right->C != 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 / operators. */
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
1846
1847 static void parseadd (ExprDesc* Expr)
1848 /* Parse an expression with the binary plus operator. Expr contains the
1849  * unprocessed left hand side of the expression and will contain the
1850  * result of the expression on return.
1851  */
1852 {
1853     ExprDesc Expr2;
1854     unsigned flags;             /* Operation flags */
1855     CodeMark Mark;              /* Remember code position */
1856     Type* lhst;                 /* Type of left hand side */
1857     Type* rhst;                 /* Type of right hand side */
1858
1859
1860     /* Skip the PLUS token */
1861     NextToken ();
1862
1863     /* Get the left hand side type, initialize operation flags */
1864     lhst = Expr->Type;
1865     flags = 0;
1866
1867     /* Check for constness on both sides */
1868     if (ED_IsConst (Expr)) {
1869
1870         /* The left hand side is a constant of some sort. Good. Get rhs */
1871         hie9 (&Expr2);
1872         if (ED_IsConstAbs (&Expr2)) {
1873
1874             /* Right hand side is a constant numeric value. Get the rhs type */
1875             rhst = Expr2.Type;
1876
1877             /* Both expressions are constants. Check for pointer arithmetic */
1878             if (IsClassPtr (lhst) && IsClassInt (rhst)) {
1879                 /* Left is pointer, right is int, must scale rhs */
1880                 Expr->IVal += Expr2.IVal * CheckedPSizeOf (lhst);
1881                 /* Result type is a pointer */
1882             } else if (IsClassInt (lhst) && IsClassPtr (rhst)) {
1883                 /* Left is int, right is pointer, must scale lhs */
1884                 Expr->IVal = Expr->IVal * CheckedPSizeOf (rhst) + Expr2.IVal;
1885                 /* Result type is a pointer */
1886                 Expr->Type = Expr2.Type;
1887             } else if (IsClassInt (lhst) && IsClassInt (rhst)) {
1888                 /* Integer addition */
1889                 Expr->IVal += Expr2.IVal;
1890                 typeadjust (Expr, &Expr2, 1);
1891             } else {
1892                 /* OOPS */
1893                 Error ("Invalid operands for binary operator `+'");
1894             }
1895
1896         } else {
1897
1898             /* lhs is a constant and rhs is not constant. Load rhs into
1899              * the primary.
1900              */
1901             LoadExpr (CF_NONE, &Expr2);
1902
1903             /* Beware: The check above (for lhs) lets not only pass numeric
1904              * constants, but also constant addresses (labels), maybe even
1905              * with an offset. We have to check for that here.
1906              */
1907
1908             /* First, get the rhs type. */
1909             rhst = Expr2.Type;
1910
1911             /* Setup flags */
1912             if (ED_IsLocAbs (Expr)) {
1913                 /* A numerical constant */
1914                 flags |= CF_CONST;
1915             } else {
1916                 /* Constant address label */
1917                 flags |= GlobalModeFlags (Expr->Flags) | CF_CONSTADDR;
1918             }
1919
1920             /* Check for pointer arithmetic */
1921             if (IsClassPtr (lhst) && IsClassInt (rhst)) {
1922                 /* Left is pointer, right is int, must scale rhs */
1923                 g_scale (CF_INT, CheckedPSizeOf (lhst));
1924                 /* Operate on pointers, result type is a pointer */
1925                 flags |= CF_PTR;
1926                 /* Generate the code for the add */
1927                 if (ED_GetLoc (Expr) == E_LOC_ABS) {
1928                     /* Numeric constant */
1929                     g_inc (flags, Expr->IVal);
1930                 } else {
1931                     /* Constant address */
1932                     g_addaddr_static (flags, Expr->Name, Expr->IVal);
1933                 }
1934             } else if (IsClassInt (lhst) && IsClassPtr (rhst)) {
1935
1936                 /* Left is int, right is pointer, must scale lhs. */
1937                 unsigned ScaleFactor = CheckedPSizeOf (rhst);
1938
1939                 /* Operate on pointers, result type is a pointer */
1940                 flags |= CF_PTR;
1941                 Expr->Type = Expr2.Type;
1942
1943                 /* Since we do already have rhs in the primary, if lhs is
1944                  * not a numeric constant, and the scale factor is not one
1945                  * (no scaling), we must take the long way over the stack.
1946                  */
1947                 if (ED_IsLocAbs (Expr)) {
1948                     /* Numeric constant, scale lhs */
1949                     Expr->IVal *= ScaleFactor;
1950                     /* Generate the code for the add */
1951                     g_inc (flags, Expr->IVal);
1952                 } else if (ScaleFactor == 1) {
1953                     /* Constant address but no need to scale */
1954                     g_addaddr_static (flags, Expr->Name, Expr->IVal);
1955                 } else {
1956                     /* Constant address that must be scaled */
1957                     g_push (TypeOf (Expr2.Type), 0);    /* rhs --> stack */
1958                     g_getimmed (flags, Expr->Name, Expr->IVal);
1959                     g_scale (CF_PTR, ScaleFactor);
1960                     g_add (CF_PTR, 0);
1961                 }
1962             } else if (IsClassInt (lhst) && IsClassInt (rhst)) {
1963                 /* Integer addition */
1964                 flags |= typeadjust (Expr, &Expr2, 1);
1965                 /* Generate the code for the add */
1966                 if (ED_IsLocAbs (Expr)) {
1967                     /* Numeric constant */
1968                     g_inc (flags, Expr->IVal);
1969                 } else {
1970                     /* Constant address */
1971                     g_addaddr_static (flags, Expr->Name, Expr->IVal);
1972                 }
1973             } else {
1974                 /* OOPS */
1975                 Error ("Invalid operands for binary operator `+'");
1976             }
1977
1978             /* Result is a rvalue in primary register */
1979             ED_MakeRValExpr (Expr);
1980         }
1981
1982     } else {
1983
1984         /* Left hand side is not constant. Get the value onto the stack. */
1985         LoadExpr (CF_NONE, Expr);              /* --> primary register */
1986         GetCodePos (&Mark);
1987         g_push (TypeOf (Expr->Type), 0);        /* --> stack */
1988
1989         /* Evaluate the rhs */
1990         if (evalexpr (CF_NONE, hie9, &Expr2) == 0) {
1991
1992             /* Right hand side is a constant. Get the rhs type */
1993             rhst = Expr2.Type;
1994
1995             /* Remove pushed value from stack */
1996             RemoveCode (&Mark);
1997
1998             /* Check for pointer arithmetic */
1999             if (IsClassPtr (lhst) && IsClassInt (rhst)) {
2000                 /* Left is pointer, right is int, must scale rhs */
2001                 Expr2.IVal *= CheckedPSizeOf (lhst);
2002                 /* Operate on pointers, result type is a pointer */
2003                 flags = CF_PTR;
2004             } else if (IsClassInt (lhst) && IsClassPtr (rhst)) {
2005                 /* Left is int, right is pointer, must scale lhs (ptr only) */
2006                 g_scale (CF_INT | CF_CONST, CheckedPSizeOf (rhst));
2007                 /* Operate on pointers, result type is a pointer */
2008                 flags = CF_PTR;
2009                 Expr->Type = Expr2.Type;
2010             } else if (IsClassInt (lhst) && IsClassInt (rhst)) {
2011                 /* Integer addition */
2012                 flags = typeadjust (Expr, &Expr2, 1);
2013             } else {
2014                 /* OOPS */
2015                 Error ("Invalid operands for binary operator `+'");
2016             }
2017
2018             /* Generate code for the add */
2019             g_inc (flags | CF_CONST, Expr2.IVal);
2020
2021         } else {
2022
2023             /* lhs and rhs are not constant. Get the rhs type. */
2024             rhst = Expr2.Type;
2025
2026             /* Check for pointer arithmetic */
2027             if (IsClassPtr (lhst) && IsClassInt (rhst)) {
2028                 /* Left is pointer, right is int, must scale rhs */
2029                 g_scale (CF_INT, CheckedPSizeOf (lhst));
2030                 /* Operate on pointers, result type is a pointer */
2031                 flags = CF_PTR;
2032             } else if (IsClassInt (lhst) && IsClassPtr (rhst)) {
2033                 /* Left is int, right is pointer, must scale lhs */
2034                 g_tosint (TypeOf (rhst));       /* Make sure, TOS is int */
2035                 g_swap (CF_INT);                /* Swap TOS and primary */
2036                 g_scale (CF_INT, CheckedPSizeOf (rhst));
2037                 /* Operate on pointers, result type is a pointer */
2038                 flags = CF_PTR;
2039                 Expr->Type = Expr2.Type;
2040             } else if (IsClassInt (lhst) && IsClassInt (rhst)) {
2041                 /* Integer addition. Note: Result is never constant.
2042                  * Problem here is that typeadjust does not know if the
2043                  * variable is an rvalue or lvalue, so if both operands
2044                  * are dereferenced constant numeric addresses, typeadjust
2045                  * thinks the operation works on constants. Removing
2046                  * CF_CONST here means handling the symptoms, however, the
2047                  * whole parser is such a mess that I fear to break anything
2048                  * when trying to apply another solution.
2049                  */
2050                 flags = typeadjust (Expr, &Expr2, 0) & ~CF_CONST;
2051             } else {
2052                 /* OOPS */
2053                 Error ("Invalid operands for binary operator `+'");
2054             }
2055
2056             /* Generate code for the add */
2057             g_add (flags, 0);
2058
2059         }
2060
2061         /* Result is a rvalue in primary register */
2062         ED_MakeRValExpr (Expr);
2063     }
2064
2065     /* Condition codes not set */
2066     ED_MarkAsUntested (Expr);
2067
2068 }
2069
2070
2071
2072 static void parsesub (ExprDesc* Expr)
2073 /* Parse an expression with the binary minus operator. Expr contains the
2074  * unprocessed left hand side of the expression and will contain the
2075  * result of the expression on return.
2076  */
2077 {
2078     ExprDesc Expr2;
2079     unsigned flags;             /* Operation flags */
2080     Type* lhst;                 /* Type of left hand side */
2081     Type* rhst;                 /* Type of right hand side */
2082     CodeMark Mark1;             /* Save position of output queue */
2083     CodeMark Mark2;             /* Another position in the queue */
2084     int rscale;                 /* Scale factor for the result */
2085
2086
2087     /* Skip the MINUS token */
2088     NextToken ();
2089
2090     /* Get the left hand side type, initialize operation flags */
2091     lhst = Expr->Type;
2092     flags = 0;
2093     rscale = 1;                 /* Scale by 1, that is, don't scale */
2094
2095     /* Remember the output queue position, then bring the value onto the stack */
2096     GetCodePos (&Mark1);
2097     LoadExpr (CF_NONE, Expr);  /* --> primary register */
2098     GetCodePos (&Mark2);
2099     g_push (TypeOf (lhst), 0);  /* --> stack */
2100
2101     /* Parse the right hand side */
2102     if (evalexpr (CF_NONE, hie9, &Expr2) == 0) {
2103
2104         /* The right hand side is constant. Get the rhs type. */
2105         rhst = Expr2.Type;
2106
2107         /* Check left hand side */
2108         if (ED_IsConstAbs (Expr)) {
2109
2110             /* Both sides are constant, remove generated code */
2111             RemoveCode (&Mark1);
2112
2113             /* Check for pointer arithmetic */
2114             if (IsClassPtr (lhst) && IsClassInt (rhst)) {
2115                 /* Left is pointer, right is int, must scale rhs */
2116                 Expr->IVal -= Expr2.IVal * CheckedPSizeOf (lhst);
2117                 /* Operate on pointers, result type is a pointer */
2118             } else if (IsClassPtr (lhst) && IsClassPtr (rhst)) {
2119                 /* Left is pointer, right is pointer, must scale result */
2120                 if (TypeCmp (Indirect (lhst), Indirect (rhst)) < TC_QUAL_DIFF) {
2121                     Error ("Incompatible pointer types");
2122                 } else {
2123                     Expr->IVal = (Expr->IVal - Expr2.IVal) /
2124                                       CheckedPSizeOf (lhst);
2125                 }
2126                 /* Operate on pointers, result type is an integer */
2127                 Expr->Type = type_int;
2128             } else if (IsClassInt (lhst) && IsClassInt (rhst)) {
2129                 /* Integer subtraction */
2130                 typeadjust (Expr, &Expr2, 1);
2131                 Expr->IVal -= Expr2.IVal;
2132             } else {
2133                 /* OOPS */
2134                 Error ("Invalid operands for binary operator `-'");
2135             }
2136
2137             /* Result is constant, condition codes not set */
2138             ED_MarkAsUntested (Expr);
2139
2140         } else {
2141
2142             /* Left hand side is not constant, right hand side is.
2143              * Remove pushed value from stack.
2144              */
2145             RemoveCode (&Mark2);
2146
2147             if (IsClassPtr (lhst) && IsClassInt (rhst)) {
2148                 /* Left is pointer, right is int, must scale rhs */
2149                 Expr2.IVal *= CheckedPSizeOf (lhst);
2150                 /* Operate on pointers, result type is a pointer */
2151                 flags = CF_PTR;
2152             } else if (IsClassPtr (lhst) && IsClassPtr (rhst)) {
2153                 /* Left is pointer, right is pointer, must scale result */
2154                 if (TypeCmp (Indirect (lhst), Indirect (rhst)) < TC_QUAL_DIFF) {
2155                     Error ("Incompatible pointer types");
2156                 } else {
2157                     rscale = CheckedPSizeOf (lhst);
2158                 }
2159                 /* Operate on pointers, result type is an integer */
2160                 flags = CF_PTR;
2161                 Expr->Type = type_int;
2162             } else if (IsClassInt (lhst) && IsClassInt (rhst)) {
2163                 /* Integer subtraction */
2164                 flags = typeadjust (Expr, &Expr2, 1);
2165             } else {
2166                 /* OOPS */
2167                 Error ("Invalid operands for binary operator `-'");
2168             }
2169
2170             /* Do the subtraction */
2171             g_dec (flags | CF_CONST, Expr2.IVal);
2172
2173             /* If this was a pointer subtraction, we must scale the result */
2174             if (rscale != 1) {
2175                 g_scale (flags, -rscale);
2176             }
2177
2178             /* Result is a rvalue in the primary register */
2179             ED_MakeRValExpr (Expr);
2180             ED_MarkAsUntested (Expr);
2181
2182         }
2183
2184     } else {
2185
2186         /* Right hand side is not constant. Get the rhs type. */
2187         rhst = Expr2.Type;
2188
2189         /* Check for pointer arithmetic */
2190         if (IsClassPtr (lhst) && IsClassInt (rhst)) {
2191             /* Left is pointer, right is int, must scale rhs */
2192             g_scale (CF_INT, CheckedPSizeOf (lhst));
2193             /* Operate on pointers, result type is a pointer */
2194             flags = CF_PTR;
2195         } else if (IsClassPtr (lhst) && IsClassPtr (rhst)) {
2196             /* Left is pointer, right is pointer, must scale result */
2197             if (TypeCmp (Indirect (lhst), Indirect (rhst)) < TC_QUAL_DIFF) {
2198                 Error ("Incompatible pointer types");
2199             } else {
2200                 rscale = CheckedPSizeOf (lhst);
2201             }
2202             /* Operate on pointers, result type is an integer */
2203             flags = CF_PTR;
2204             Expr->Type = type_int;
2205         } else if (IsClassInt (lhst) && IsClassInt (rhst)) {
2206             /* Integer subtraction. If the left hand side descriptor says that
2207              * the lhs is const, we have to remove this mark, since this is no
2208              * longer true, lhs is on stack instead.
2209              */
2210             if (ED_IsLocAbs (Expr)) {
2211                 ED_MakeRValExpr (Expr);
2212             }
2213             /* Adjust operand types */
2214             flags = typeadjust (Expr, &Expr2, 0);
2215         } else {
2216             /* OOPS */
2217             Error ("Invalid operands for binary operator `-'");
2218         }
2219
2220         /* Generate code for the sub (the & is a hack here) */
2221         g_sub (flags & ~CF_CONST, 0);
2222
2223         /* If this was a pointer subtraction, we must scale the result */
2224         if (rscale != 1) {
2225             g_scale (flags, -rscale);
2226         }
2227
2228         /* Result is a rvalue in the primary register */
2229         ED_MakeRValExpr (Expr);
2230         ED_MarkAsUntested (Expr);
2231     }
2232 }
2233
2234
2235
2236 void hie8 (ExprDesc* Expr)
2237 /* Process + and - binary operators. */
2238 {
2239     hie9 (Expr);
2240     while (CurTok.Tok == TOK_PLUS || CurTok.Tok == TOK_MINUS) {
2241         if (CurTok.Tok == TOK_PLUS) {
2242             parseadd (Expr);
2243         } else {
2244             parsesub (Expr);
2245         }
2246     }
2247 }
2248
2249
2250
2251 static void hie6 (ExprDesc* Expr)
2252 /* Handle greater-than type comparators */
2253 {
2254     static const GenDesc hie6_ops [] = {
2255         { TOK_LT,       GEN_NOPUSH,     g_lt    },
2256         { TOK_LE,       GEN_NOPUSH,     g_le    },
2257         { TOK_GE,       GEN_NOPUSH,     g_ge    },
2258         { TOK_GT,       GEN_NOPUSH,     g_gt    },
2259         { TOK_INVALID,  0,              0       }
2260     };
2261     hie_compare (hie6_ops, Expr, ShiftExpr);
2262 }
2263
2264
2265
2266 static void hie5 (ExprDesc* Expr)
2267 /* Handle == and != */
2268 {
2269     static const GenDesc hie5_ops[] = {
2270         { TOK_EQ,       GEN_NOPUSH,     g_eq    },
2271         { TOK_NE,       GEN_NOPUSH,     g_ne    },
2272         { TOK_INVALID,  0,              0       }
2273     };
2274     hie_compare (hie5_ops, Expr, hie6);
2275 }
2276
2277
2278
2279 static void hie4 (ExprDesc* Expr)
2280 /* Handle & (bitwise and) */
2281 {
2282     static const GenDesc hie4_ops[] = {
2283         { TOK_AND,      GEN_NOPUSH,     g_and   },
2284         { TOK_INVALID,  0,              0       }
2285     };
2286     int UsedGen;
2287
2288     hie_internal (hie4_ops, Expr, hie5, &UsedGen);
2289 }
2290
2291
2292
2293 static void hie3 (ExprDesc* Expr)
2294 /* Handle ^ (bitwise exclusive or) */
2295 {
2296     static const GenDesc hie3_ops[] = {
2297         { TOK_XOR,      GEN_NOPUSH,     g_xor   },
2298         { TOK_INVALID,  0,              0       }
2299     };
2300     int UsedGen;
2301
2302     hie_internal (hie3_ops, Expr, hie4, &UsedGen);
2303 }
2304
2305
2306
2307 static void hie2 (ExprDesc* Expr)
2308 /* Handle | (bitwise or) */
2309 {
2310     static const GenDesc hie2_ops[] = {
2311         { TOK_OR,       GEN_NOPUSH,     g_or    },
2312         { TOK_INVALID,  0,              0       }
2313     };
2314     int UsedGen;
2315
2316     hie_internal (hie2_ops, Expr, hie3, &UsedGen);
2317 }
2318
2319
2320
2321 static void hieAndPP (ExprDesc* Expr)
2322 /* Process "exp && exp" in preprocessor mode (that is, when the parser is
2323  * called recursively from the preprocessor.
2324  */
2325 {
2326     ExprDesc Expr2;
2327
2328     ConstAbsIntExpr (hie2, Expr);
2329     while (CurTok.Tok == TOK_BOOL_AND) {
2330
2331         /* Skip the && */
2332         NextToken ();
2333
2334         /* Get rhs */
2335         ConstAbsIntExpr (hie2, &Expr2);
2336
2337         /* Combine the two */
2338         Expr->IVal = (Expr->IVal && Expr2.IVal);
2339     }
2340 }
2341
2342
2343
2344 static void hieOrPP (ExprDesc *Expr)
2345 /* Process "exp || exp" in preprocessor mode (that is, when the parser is
2346  * called recursively from the preprocessor.
2347  */
2348 {
2349     ExprDesc Expr2;
2350
2351     ConstAbsIntExpr (hieAndPP, Expr);
2352     while (CurTok.Tok == TOK_BOOL_OR) {
2353
2354         /* Skip the && */
2355         NextToken ();
2356
2357         /* Get rhs */
2358         ConstAbsIntExpr (hieAndPP, &Expr2);
2359
2360         /* Combine the two */
2361         Expr->IVal = (Expr->IVal || Expr2.IVal);
2362     }
2363 }
2364
2365
2366
2367 static void hieAnd (ExprDesc* Expr, unsigned TrueLab, int* BoolOp)
2368 /* Process "exp && exp" */
2369 {
2370     int lab;
2371     ExprDesc Expr2;
2372
2373     hie2 (Expr);
2374     if (CurTok.Tok == TOK_BOOL_AND) {
2375
2376         /* Tell our caller that we're evaluating a boolean */
2377         *BoolOp = 1;
2378
2379         /* Get a label that we will use for false expressions */
2380         lab = GetLocalLabel ();
2381
2382         /* If the expr hasn't set condition codes, set the force-test flag */
2383         if (!ED_IsTested (Expr)) {
2384             ED_MarkForTest (Expr);
2385         }
2386
2387         /* Load the value */
2388         LoadExpr (CF_FORCECHAR, Expr);
2389
2390         /* Generate the jump */
2391         g_falsejump (CF_NONE, lab);
2392
2393         /* Parse more boolean and's */
2394         while (CurTok.Tok == TOK_BOOL_AND) {
2395
2396             /* Skip the && */
2397             NextToken ();
2398
2399             /* Get rhs */
2400             hie2 (&Expr2);
2401             if (!ED_IsTested (&Expr2)) {
2402                 ED_MarkForTest (&Expr2);
2403             }
2404             LoadExpr (CF_FORCECHAR, &Expr2);
2405
2406             /* Do short circuit evaluation */
2407             if (CurTok.Tok == TOK_BOOL_AND) {
2408                 g_falsejump (CF_NONE, lab);
2409             } else {
2410                 /* Last expression - will evaluate to true */
2411                 g_truejump (CF_NONE, TrueLab);
2412             }
2413         }
2414
2415         /* Define the false jump label here */
2416         g_defcodelabel (lab);
2417
2418         /* The result is an rvalue in primary */
2419         ED_MakeRValExpr (Expr);
2420         ED_TestDone (Expr);     /* Condition codes are set */
2421     }
2422 }
2423
2424
2425
2426 static void hieOr (ExprDesc *Expr)
2427 /* Process "exp || exp". */
2428 {
2429     ExprDesc Expr2;
2430     int BoolOp = 0;             /* Did we have a boolean op? */
2431     int AndOp;                  /* Did we have a && operation? */
2432     unsigned TrueLab;           /* Jump to this label if true */
2433     unsigned DoneLab;
2434
2435     /* Get a label */
2436     TrueLab = GetLocalLabel ();
2437
2438     /* Call the next level parser */
2439     hieAnd (Expr, TrueLab, &BoolOp);
2440
2441     /* Any boolean or's? */
2442     if (CurTok.Tok == TOK_BOOL_OR) {
2443
2444         /* If the expr hasn't set condition codes, set the force-test flag */
2445         if (!ED_IsTested (Expr)) {
2446             ED_MarkForTest (Expr);
2447         }
2448
2449         /* Get first expr */
2450         LoadExpr (CF_FORCECHAR, Expr);
2451
2452         /* For each expression jump to TrueLab if true. Beware: If we
2453          * had && operators, the jump is already in place!
2454          */
2455         if (!BoolOp) {
2456             g_truejump (CF_NONE, TrueLab);
2457         }
2458
2459         /* Remember that we had a boolean op */
2460         BoolOp = 1;
2461
2462         /* while there's more expr */
2463         while (CurTok.Tok == TOK_BOOL_OR) {
2464
2465             /* skip the || */
2466             NextToken ();
2467
2468             /* Get a subexpr */
2469             AndOp = 0;
2470             hieAnd (&Expr2, TrueLab, &AndOp);
2471             if (!ED_IsTested (&Expr2)) {
2472                 ED_MarkForTest (&Expr2);
2473             }
2474             LoadExpr (CF_FORCECHAR, &Expr2);
2475
2476             /* If there is more to come, add shortcut boolean eval. */
2477             g_truejump (CF_NONE, TrueLab);
2478
2479         }
2480
2481         /* The result is an rvalue in primary */
2482         ED_MakeRValExpr (Expr);
2483         ED_TestDone (Expr);                     /* Condition codes are set */
2484     }
2485
2486     /* If we really had boolean ops, generate the end sequence */
2487     if (BoolOp) {
2488         DoneLab = GetLocalLabel ();
2489         g_getimmed (CF_INT | CF_CONST, 0, 0);   /* Load FALSE */
2490         g_falsejump (CF_NONE, DoneLab);
2491         g_defcodelabel (TrueLab);
2492         g_getimmed (CF_INT | CF_CONST, 1, 0);   /* Load TRUE */
2493         g_defcodelabel (DoneLab);
2494     }
2495 }
2496
2497
2498
2499 static void hieQuest (ExprDesc* Expr)
2500 /* Parse the ternary operator */
2501 {
2502     int         labf;
2503     int         labt;
2504     ExprDesc    Expr2;          /* Expression 2 */
2505     ExprDesc    Expr3;          /* Expression 3 */
2506     int         Expr2IsNULL;    /* Expression 2 is a NULL pointer */
2507     int         Expr3IsNULL;    /* Expression 3 is a NULL pointer */
2508     Type*       ResultType;     /* Type of result */
2509
2510
2511     /* Call the lower level eval routine */
2512     if (Preprocessing) {
2513         hieOrPP (Expr);
2514     } else {
2515         hieOr (Expr);
2516     }
2517
2518     /* Check if it's a ternary expression */
2519     if (CurTok.Tok == TOK_QUEST) {
2520         NextToken ();
2521         if (!ED_IsTested (Expr)) {
2522             /* Condition codes not set, request a test */
2523             ED_MarkForTest (Expr);
2524         }
2525         LoadExpr (CF_NONE, Expr);
2526         labf = GetLocalLabel ();
2527         g_falsejump (CF_NONE, labf);
2528
2529         /* Parse second expression. Remember for later if it is a NULL pointer
2530          * expression, then load it into the primary.
2531          */
2532         ExprWithCheck (hie1, &Expr2);
2533         Expr2IsNULL = ED_IsNullPtr (&Expr2);
2534         if (!IsTypeVoid (Expr2.Type)) {
2535             /* Load it into the primary */
2536             LoadExpr (CF_NONE, &Expr2);
2537             ED_MakeRValExpr (&Expr2);
2538         }
2539         labt = GetLocalLabel ();
2540         ConsumeColon ();
2541         g_jump (labt);
2542
2543         /* Jump here if the first expression was false */
2544         g_defcodelabel (labf);
2545
2546         /* Parse second expression. Remember for later if it is a NULL pointer
2547          * expression, then load it into the primary.
2548          */
2549         ExprWithCheck (hie1, &Expr3);
2550         Expr3IsNULL = ED_IsNullPtr (&Expr3);
2551         if (!IsTypeVoid (Expr3.Type)) {
2552             /* Load it into the primary */
2553             LoadExpr (CF_NONE, &Expr3);
2554             ED_MakeRValExpr (&Expr3);
2555         }
2556
2557         /* Check if any conversions are needed, if so, do them.
2558          * Conversion rules for ?: expression are:
2559          *   - if both expressions are int expressions, default promotion
2560          *     rules for ints apply.
2561          *   - if both expressions are pointers of the same type, the
2562          *     result of the expression is of this type.
2563          *   - if one of the expressions is a pointer and the other is
2564          *     a zero constant, the resulting type is that of the pointer
2565          *     type.
2566          *   - if both expressions are void expressions, the result is of
2567          *     type void.
2568          *   - all other cases are flagged by an error.
2569          */
2570         if (IsClassInt (Expr2.Type) && IsClassInt (Expr3.Type)) {
2571
2572             /* Get common type */
2573             ResultType = promoteint (Expr2.Type, Expr3.Type);
2574
2575             /* Convert the third expression to this type if needed */
2576             TypeConversion (&Expr3, ResultType);
2577
2578             /* Setup a new label so that the expr3 code will jump around
2579              * the type cast code for expr2.
2580              */
2581             labf = GetLocalLabel ();    /* Get new label */
2582             g_jump (labf);              /* Jump around code */
2583
2584             /* The jump for expr2 goes here */
2585             g_defcodelabel (labt);
2586
2587             /* Create the typecast code for expr2 */
2588             TypeConversion (&Expr2, ResultType);
2589
2590             /* Jump here around the typecase code. */
2591             g_defcodelabel (labf);
2592             labt = 0;           /* Mark other label as invalid */
2593
2594         } else if (IsClassPtr (Expr2.Type) && IsClassPtr (Expr3.Type)) {
2595             /* Must point to same type */
2596             if (TypeCmp (Indirect (Expr2.Type), Indirect (Expr3.Type)) < TC_EQUAL) {
2597                 Error ("Incompatible pointer types");
2598             }
2599             /* Result has the common type */
2600             ResultType = Expr2.Type;
2601         } else if (IsClassPtr (Expr2.Type) && Expr3IsNULL) {
2602             /* Result type is pointer, no cast needed */
2603             ResultType = Expr2.Type;
2604         } else if (Expr2IsNULL && IsClassPtr (Expr3.Type)) {
2605             /* Result type is pointer, no cast needed */
2606             ResultType = Expr3.Type;
2607         } else if (IsTypeVoid (Expr2.Type) && IsTypeVoid (Expr3.Type)) {
2608             /* Result type is void */
2609             ResultType = Expr3.Type;
2610         } else {
2611             Error ("Incompatible types");
2612             ResultType = Expr2.Type;            /* Doesn't matter here */
2613         }
2614
2615         /* If we don't have the label defined until now, do it */
2616         if (labt) {
2617             g_defcodelabel (labt);
2618         }
2619
2620         /* Setup the target expression */
2621         ED_MakeRValExpr (Expr);
2622         Expr->Type  = ResultType;
2623     }
2624 }
2625
2626
2627
2628 static void opeq (const GenDesc* Gen, ExprDesc* Expr)
2629 /* Process "op=" operators. */
2630 {
2631     ExprDesc Expr2;
2632     unsigned flags;
2633     CodeMark Mark;
2634     int MustScale;
2635
2636     /* op= can only be used with lvalues */
2637     if (!ED_IsLVal (Expr)) {
2638         Error ("Invalid lvalue in assignment");
2639         return;
2640     }
2641
2642     /* There must be an integer or pointer on the left side */
2643     if (!IsClassInt (Expr->Type) && !IsTypePtr (Expr->Type)) {
2644         Error ("Invalid left operand type");
2645         /* Continue. Wrong code will be generated, but the compiler won't
2646          * break, so this is the best error recovery.
2647          */
2648     }
2649
2650     /* Skip the operator token */
2651     NextToken ();
2652
2653     /* Determine the type of the lhs */
2654     flags = TypeOf (Expr->Type);
2655     MustScale = (Gen->Func == g_add || Gen->Func == g_sub) && IsTypePtr (Expr->Type);
2656
2657     /* Get the lhs address on stack (if needed) */
2658     PushAddr (Expr);
2659
2660     /* Fetch the lhs into the primary register if needed */
2661     LoadExpr (CF_NONE, Expr);
2662
2663     /* Bring the lhs on stack */
2664     GetCodePos (&Mark);
2665     g_push (flags, 0);
2666
2667     /* Evaluate the rhs */
2668     if (evalexpr (CF_NONE, hie1, &Expr2) == 0) {
2669         /* The resulting value is a constant. If the generator has the NOPUSH
2670          * flag set, don't push the lhs.
2671          */
2672         if (Gen->Flags & GEN_NOPUSH) {
2673             RemoveCode (&Mark);
2674         }
2675         if (MustScale) {
2676             /* lhs is a pointer, scale rhs */
2677             Expr2.IVal *= CheckedSizeOf (Expr->Type+1);
2678         }
2679
2680         /* If the lhs is character sized, the operation may be later done
2681          * with characters.
2682          */
2683         if (CheckedSizeOf (Expr->Type) == SIZEOF_CHAR) {
2684             flags |= CF_FORCECHAR;
2685         }
2686
2687         /* Special handling for add and sub - some sort of a hack, but short code */
2688         if (Gen->Func == g_add) {
2689             g_inc (flags | CF_CONST, Expr2.IVal);
2690         } else if (Gen->Func == g_sub) {
2691             g_dec (flags | CF_CONST, Expr2.IVal);
2692         } else {
2693             Gen->Func (flags | CF_CONST, Expr2.IVal);
2694         }
2695     } else {
2696         /* rhs is not constant and already in the primary register */
2697         if (MustScale) {
2698             /* lhs is a pointer, scale rhs */
2699             g_scale (TypeOf (Expr2.Type), CheckedSizeOf (Expr->Type+1));
2700         }
2701
2702         /* If the lhs is character sized, the operation may be later done
2703          * with characters.
2704          */
2705         if (CheckedSizeOf (Expr->Type) == SIZEOF_CHAR) {
2706             flags |= CF_FORCECHAR;
2707         }
2708
2709         /* Adjust the types of the operands if needed */
2710         Gen->Func (g_typeadjust (flags, TypeOf (Expr2.Type)), 0);
2711     }
2712     Store (Expr, 0);
2713     ED_MakeRValExpr (Expr);
2714 }
2715
2716
2717
2718 static void addsubeq (const GenDesc* Gen, ExprDesc *Expr)
2719 /* Process the += and -= operators */
2720 {
2721     ExprDesc Expr2;
2722     unsigned lflags;
2723     unsigned rflags;
2724     int      MustScale;
2725
2726
2727     /* We're currently only able to handle some adressing modes */
2728     if (ED_GetLoc (Expr) == E_LOC_EXPR || ED_GetLoc (Expr) == E_LOC_PRIMARY) {
2729         /* Use generic routine */
2730         opeq (Gen, Expr);
2731         return;
2732     }
2733
2734     /* We must have an lvalue */
2735     if (ED_IsRVal (Expr)) {
2736         Error ("Invalid lvalue in assignment");
2737         return;
2738     }
2739
2740     /* There must be an integer or pointer on the left side */
2741     if (!IsClassInt (Expr->Type) && !IsTypePtr (Expr->Type)) {
2742         Error ("Invalid left operand type");
2743         /* Continue. Wrong code will be generated, but the compiler won't
2744          * break, so this is the best error recovery.
2745          */
2746     }
2747
2748     /* Skip the operator */
2749     NextToken ();
2750
2751     /* Check if we have a pointer expression and must scale rhs */
2752     MustScale = IsTypePtr (Expr->Type);
2753
2754     /* Initialize the code generator flags */
2755     lflags = 0;
2756     rflags = 0;
2757
2758     /* Evaluate the rhs */
2759     hie1 (&Expr2);
2760     if (ED_IsConstAbs (&Expr2)) {
2761         /* The resulting value is a constant. Scale it. */
2762         if (MustScale) {
2763             Expr2.IVal *= CheckedSizeOf (Indirect (Expr->Type));
2764         }
2765         rflags |= CF_CONST;
2766         lflags |= CF_CONST;
2767     } else {
2768         /* Not constant, load into the primary */
2769         LoadExpr (CF_NONE, &Expr2);
2770         if (MustScale) {
2771             /* lhs is a pointer, scale rhs */
2772             g_scale (TypeOf (Expr2.Type), CheckedSizeOf (Indirect (Expr->Type)));
2773         }
2774     }
2775
2776     /* Setup the code generator flags */
2777     lflags |= TypeOf (Expr->Type) | CF_FORCECHAR;
2778     rflags |= TypeOf (Expr2.Type);
2779
2780     /* Convert the type of the lhs to that of the rhs */
2781     g_typecast (lflags, rflags);
2782
2783     /* Output apropriate code depending on the location */
2784     switch (ED_GetLoc (Expr)) {
2785
2786         case E_LOC_ABS:
2787             /* Absolute: numeric address or const */
2788             lflags |= CF_ABSOLUTE;
2789             if (Gen->Tok == TOK_PLUS_ASSIGN) {
2790                 g_addeqstatic (lflags, Expr->Name, Expr->IVal, Expr2.IVal);
2791             } else {
2792                 g_subeqstatic (lflags, Expr->Name, Expr->IVal, Expr2.IVal);
2793             }
2794             break;
2795
2796         case E_LOC_GLOBAL:
2797             /* Global variable */
2798             lflags |= CF_EXTERNAL;
2799             if (Gen->Tok == TOK_PLUS_ASSIGN) {
2800                 g_addeqstatic (lflags, Expr->Name, Expr->IVal, Expr2.IVal);
2801             } else {
2802                 g_subeqstatic (lflags, Expr->Name, Expr->IVal, Expr2.IVal);
2803             }
2804             break;
2805
2806         case E_LOC_STATIC:
2807         case E_LOC_LITERAL:
2808             /* Static variable or literal in the literal pool */
2809             lflags |= CF_STATIC;
2810             if (Gen->Tok == TOK_PLUS_ASSIGN) {
2811                 g_addeqstatic (lflags, Expr->Name, Expr->IVal, Expr2.IVal);
2812             } else {
2813                 g_subeqstatic (lflags, Expr->Name, Expr->IVal, Expr2.IVal);
2814             }
2815             break;
2816
2817         case E_LOC_REGISTER:
2818             /* Register variable */
2819             lflags |= CF_REGVAR;
2820             if (Gen->Tok == TOK_PLUS_ASSIGN) {
2821                 g_addeqstatic (lflags, Expr->Name, Expr->IVal, Expr2.IVal);
2822             } else {
2823                 g_subeqstatic (lflags, Expr->Name, Expr->IVal, Expr2.IVal);
2824             }
2825             break;
2826
2827         case E_LOC_STACK:
2828             /* Value on the stack */
2829             if (Gen->Tok == TOK_PLUS_ASSIGN) {
2830                 g_addeqlocal (lflags, Expr->IVal, Expr2.IVal);
2831             } else {
2832                 g_subeqlocal (lflags, Expr->IVal, Expr2.IVal);
2833             }
2834             break;
2835
2836         default:
2837             Internal ("Invalid location in Store(): 0x%04X", ED_GetLoc (Expr));
2838     }
2839
2840     /* Expression is a rvalue in the primary now */
2841     ED_MakeRValExpr (Expr);
2842 }
2843
2844
2845
2846 void hie1 (ExprDesc* Expr)
2847 /* Parse first level of expression hierarchy. */
2848 {
2849     hieQuest (Expr);
2850     switch (CurTok.Tok) {
2851
2852         case TOK_ASSIGN:
2853             Assignment (Expr);
2854             break;
2855
2856         case TOK_PLUS_ASSIGN:
2857             addsubeq (&GenPASGN, Expr);
2858             break;
2859
2860         case TOK_MINUS_ASSIGN:
2861             addsubeq (&GenSASGN, Expr);
2862             break;
2863
2864         case TOK_MUL_ASSIGN:
2865             opeq (&GenMASGN, Expr);
2866             break;
2867
2868         case TOK_DIV_ASSIGN:
2869             opeq (&GenDASGN, Expr);
2870             break;
2871
2872         case TOK_MOD_ASSIGN:
2873             opeq (&GenMOASGN, Expr);
2874             break;
2875
2876         case TOK_SHL_ASSIGN:
2877             opeq (&GenSLASGN, Expr);
2878             break;
2879
2880         case TOK_SHR_ASSIGN:
2881             opeq (&GenSRASGN, Expr);
2882             break;
2883
2884         case TOK_AND_ASSIGN:
2885             opeq (&GenAASGN, Expr);
2886             break;
2887
2888         case TOK_XOR_ASSIGN:
2889             opeq (&GenXOASGN, Expr);
2890             break;
2891
2892         case TOK_OR_ASSIGN:
2893             opeq (&GenOASGN, Expr);
2894             break;
2895
2896         default:
2897             break;
2898     }
2899 }
2900
2901
2902
2903 void hie0 (ExprDesc *Expr)
2904 /* Parse comma operator. */
2905 {
2906     hie1 (Expr);
2907     while (CurTok.Tok == TOK_COMMA) {
2908         NextToken ();
2909         hie1 (Expr);
2910     }
2911 }
2912
2913
2914
2915 int evalexpr (unsigned Flags, void (*Func) (ExprDesc*), ExprDesc* Expr)
2916 /* Will evaluate an expression via the given function. If the result is a
2917  * constant, 0 is returned and the value is put in the Expr struct. If the
2918  * result is not constant, LoadExpr is called to bring the value into the
2919  * primary register and 1 is returned.
2920  */
2921 {
2922     /* Evaluate */
2923     ExprWithCheck (Func, Expr);
2924
2925     /* Check for a constant expression */
2926     if (ED_IsConstAbs (Expr)) {
2927         /* Constant expression */
2928         return 0;
2929     } else {
2930         /* Not constant, load into the primary */
2931         LoadExpr (Flags, Expr);
2932         return 1;
2933     }
2934 }
2935
2936
2937
2938 void Expression0 (ExprDesc* Expr)
2939 /* Evaluate an expression via hie0 and put the result into the primary register */
2940 {
2941     ExprWithCheck (hie0, Expr);
2942     LoadExpr (CF_NONE, Expr);
2943 }
2944
2945
2946
2947 void ConstExpr (void (*Func) (ExprDesc*), ExprDesc* Expr)
2948 /* Will evaluate an expression via the given function. If the result is not
2949  * a constant of some sort, a diagnostic will be printed, and the value is
2950  * replaced by a constant one to make sure there are no internal errors that
2951  * result from this input error.
2952  */
2953 {
2954     ExprWithCheck (Func, Expr);
2955     if (!ED_IsConst (Expr)) {
2956         Error ("Constant expression expected");
2957         /* To avoid any compiler errors, make the expression a valid const */
2958         ED_MakeConstAbsInt (Expr, 1);
2959     }
2960 }
2961
2962
2963
2964 void BoolExpr (void (*Func) (ExprDesc*), ExprDesc* Expr)
2965 /* Will evaluate an expression via the given function. If the result is not
2966  * something that may be evaluated in a boolean context, a diagnostic will be
2967  * printed, and the value is replaced by a constant one to make sure there
2968  * are no internal errors that result from this input error.
2969  */
2970 {
2971     ExprWithCheck (Func, Expr);
2972     if (!ED_IsBool (Expr)) {
2973         Error ("Boolean expression expected");
2974         /* To avoid any compiler errors, make the expression a valid int */
2975         ED_MakeConstAbsInt (Expr, 1);
2976     }
2977 }
2978
2979
2980
2981 void ConstAbsIntExpr (void (*Func) (ExprDesc*), ExprDesc* Expr)
2982 /* Will evaluate an expression via the given function. If the result is not
2983  * a constant numeric integer value, a diagnostic will be printed, and the
2984  * value is replaced by a constant one to make sure there are no internal
2985  * errors that result from this input error.
2986  */
2987 {
2988     ExprWithCheck (Func, Expr);
2989     if (!ED_IsConstAbsInt (Expr)) {
2990         Error ("Constant integer expression expected");
2991         /* To avoid any compiler errors, make the expression a valid const */
2992         ED_MakeConstAbsInt (Expr, 1);
2993     }
2994 }
2995
2996
2997