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