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