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